From cb4aea394e6851ae8cc45a68beeaf2c93cc9a0c0 Mon Sep 17 00:00:00 2001 From: Carl Lerche Date: Tue, 14 May 2019 10:27:36 -0700 Subject: [PATCH] Update Tokio to Rust 2018 (#1082) --- CONTRIBUTING.md | 4 - README.md | 2 - async-await/Cargo.toml | 20 +- async-await/src/chat.rs | 14 +- async-await/src/echo_client.rs | 10 +- async-await/src/echo_server.rs | 8 +- async-await/src/hyper.rs | 6 +- async-await/tests/macros.rs | 4 +- azure-pipelines.yml | 8 +- ci/azure-tsan.yml | 2 +- ci/tsan | 2 + tokio-buf/Cargo.toml | 6 +- tokio-buf/README.md | 8 +- tokio-buf/src/lib.rs | 17 +- tokio-buf/src/never.rs | 4 +- tokio-buf/src/str.rs | 6 +- tokio-buf/src/u8.rs | 4 +- tokio-buf/src/util/chain.rs | 4 +- tokio-buf/src/util/collect.rs | 4 +- tokio-buf/src/util/from.rs | 6 +- tokio-buf/src/util/iter.rs | 4 +- tokio-buf/src/util/limit.rs | 2 +- tokio-buf/src/util/mod.rs | 2 +- tokio-buf/src/util/stream.rs | 2 +- tokio-buf/tests/buf_stream.rs | 4 +- tokio-buf/tests/chain.rs | 6 - tokio-buf/tests/collect.rs | 6 - tokio-buf/tests/iter.rs | 5 - tokio-buf/tests/limit.rs | 6 - tokio-buf/tests/size_hint.rs | 2 - tokio-buf/tests/stream.rs | 6 - tokio-buf/tests/string.rs | 5 - tokio-buf/tests/support.rs | 7 +- tokio-codec/Cargo.toml | 8 +- tokio-codec/README.md | 15 - tokio-codec/src/lib.rs | 12 +- tokio-codec/tests/codecs.rs | 3 +- tokio-codec/tests/framed.rs | 5 +- tokio-codec/tests/framed_read.rs | 11 +- tokio-codec/tests/framed_write.rs | 11 +- tokio-current-thread/Cargo.toml | 8 +- tokio-current-thread/src/lib.rs | 66 ++-- tokio-current-thread/src/scheduler.rs | 30 +- tokio-current-thread/tests/current_thread.rs | 48 ++- tokio-executor/Cargo.toml | 8 +- tokio-executor/src/enter.rs | 11 +- tokio-executor/src/error.rs | 2 +- tokio-executor/src/executor.rs | 29 +- tokio-executor/src/global.rs | 19 +- tokio-executor/src/lib.rs | 17 +- tokio-executor/src/park.rs | 7 +- tokio-executor/src/typed.rs | 24 +- tokio-executor/tests/executor.rs | 9 +- tokio-fs/Cargo.toml | 15 +- tokio-fs/examples/std-echo.rs | 7 +- tokio-fs/src/create_dir.rs | 5 +- tokio-fs/src/create_dir_all.rs | 5 +- tokio-fs/src/file/clone.rs | 2 - tokio-fs/src/file/create.rs | 6 +- tokio-fs/src/file/metadata.rs | 6 +- tokio-fs/src/file/mod.rs | 342 ++++++++---------- tokio-fs/src/file/open.rs | 6 +- tokio-fs/src/file/open_options.rs | 1 - tokio-fs/src/file/seek.rs | 4 +- tokio-fs/src/hard_link.rs | 5 +- tokio-fs/src/lib.rs | 46 ++- tokio-fs/src/metadata.rs | 2 - tokio-fs/src/os/unix.rs | 5 +- tokio-fs/src/os/windows/symlink_dir.rs | 5 +- tokio-fs/src/os/windows/symlink_file.rs | 5 +- tokio-fs/src/read.rs | 25 +- tokio-fs/src/read_dir.rs | 91 ++--- tokio-fs/src/read_link.rs | 5 +- tokio-fs/src/remove_dir.rs | 5 +- tokio-fs/src/remove_file.rs | 5 +- tokio-fs/src/rename.rs | 5 +- tokio-fs/src/set_permissions.rs | 5 +- tokio-fs/src/stderr.rs | 8 +- tokio-fs/src/stdin.rs | 5 +- tokio-fs/src/stdout.rs | 8 +- tokio-fs/src/symlink_metadata.rs | 2 - tokio-fs/src/write.rs | 29 +- tokio-fs/tests/dir.rs | 4 +- tokio-fs/tests/file.rs | 14 +- tokio-fs/tests/link.rs | 7 +- tokio-fs/tests/pool/mod.rs | 4 +- tokio-futures/Cargo.toml | 8 +- tokio-futures/README.md | 9 +- tokio-futures/src/{await.rs => async_wait.rs} | 5 +- tokio-futures/src/compat/forward.rs | 2 +- tokio-futures/src/compat/mod.rs | 2 +- tokio-futures/src/io/flush.rs | 7 +- tokio-futures/src/io/mod.rs | 30 +- tokio-futures/src/io/read.rs | 10 +- tokio-futures/src/io/read_exact.rs | 10 +- tokio-futures/src/io/write.rs | 10 +- tokio-futures/src/io/write_all.rs | 10 +- tokio-futures/src/lib.rs | 15 +- tokio-futures/src/sink/mod.rs | 2 +- tokio-futures/src/sink/send.rs | 8 +- tokio-futures/src/stream/mod.rs | 12 +- tokio-futures/src/stream/next.rs | 5 +- tokio-io/Cargo.toml | 6 +- tokio-io/README.md | 8 +- tokio-io/src/_tokio_codec/decoder.rs | 2 +- tokio-io/src/_tokio_codec/encoder.rs | 2 +- tokio-io/src/_tokio_codec/framed.rs | 12 +- tokio-io/src/_tokio_codec/framed_read.rs | 13 +- tokio-io/src/_tokio_codec/framed_write.rs | 15 +- tokio-io/src/_tokio_codec/mod.rs | 1 - tokio-io/src/allow_std.rs | 4 +- tokio-io/src/async_read.rs | 13 +- tokio-io/src/async_write.rs | 5 +- tokio-io/src/codec/bytes_codec.rs | 2 +- tokio-io/src/codec/decoder.rs | 8 +- tokio-io/src/codec/lines_codec.rs | 2 +- tokio-io/src/codec/mod.rs | 55 ++- tokio-io/src/framed.rs | 16 +- tokio-io/src/framed_read.rs | 15 +- tokio-io/src/framed_write.rs | 15 +- tokio-io/src/io/copy.rs | 6 +- tokio-io/src/io/flush.rs | 6 +- tokio-io/src/io/mod.rs | 8 +- tokio-io/src/io/read.rs | 6 +- tokio-io/src/io/read_exact.rs | 6 +- tokio-io/src/io/read_to_end.rs | 6 +- tokio-io/src/io/read_until.rs | 6 +- tokio-io/src/io/shutdown.rs | 6 +- tokio-io/src/io/write_all.rs | 6 +- tokio-io/src/length_delimited.rs | 35 +- tokio-io/src/lib.rs | 22 +- tokio-io/src/lines.rs | 6 +- tokio-io/src/split.rs | 12 +- tokio-io/tests/async_read.rs | 7 +- tokio-io/tests/length_delimited.rs | 9 +- tokio-macros/Cargo.toml | 2 +- tokio-macros/src/lib.rs | 5 + tokio-reactor/Cargo.toml | 12 +- tokio-reactor/benches/basic.rs | 8 +- tokio-reactor/src/background.rs | 5 +- tokio-reactor/src/lib.rs | 48 +-- tokio-reactor/src/poll_evented.rs | 17 +- tokio-reactor/src/registration.rs | 7 +- tokio-reactor/src/sharded_rwlock.rs | 16 +- tokio-signal/Cargo.toml | 14 +- tokio-signal/README.md | 4 - tokio-signal/examples/ctrl-c.rs | 9 +- tokio-signal/examples/multiple.rs | 12 +- tokio-signal/examples/sighup-example.rs | 10 +- tokio-signal/src/lib.rs | 69 ++-- tokio-signal/src/unix.rs | 15 +- tokio-signal/src/windows.rs | 19 +- tokio-signal/tests/drop_multi_loop.rs | 5 +- tokio-signal/tests/drop_then_get_a_signal.rs | 5 +- ...ing_does_not_deregister_other_instances.rs | 5 +- tokio-signal/tests/multi_loop.rs | 12 +- tokio-signal/tests/notify_both.rs | 7 +- tokio-signal/tests/signal.rs | 7 +- tokio-signal/tests/simple.rs | 7 +- tokio-signal/tests/support.rs | 16 +- tokio-signal/tests/twice.rs | 7 +- tokio-sync/Cargo.toml | 8 +- tokio-sync/benches/mpsc.rs | 4 +- tokio-sync/benches/oneshot.rs | 4 +- tokio-sync/src/lib.rs | 12 +- tokio-sync/src/lock.rs | 15 +- tokio-sync/src/loom.rs | 2 +- tokio-sync/src/mpsc/block.rs | 3 +- tokio-sync/src/mpsc/bounded.rs | 19 +- tokio-sync/src/mpsc/chan.rs | 20 +- tokio-sync/src/mpsc/list.rs | 8 +- tokio-sync/src/mpsc/mod.rs | 2 - tokio-sync/src/mpsc/unbounded.rs | 14 +- tokio-sync/src/oneshot.rs | 15 +- tokio-sync/src/semaphore.rs | 12 +- tokio-sync/src/task/atomic_task.rs | 5 +- tokio-sync/src/watch.rs | 23 +- tokio-sync/tests/atomic_task.rs | 6 +- tokio-sync/tests/errors.rs | 4 +- tokio-sync/tests/fuzz_atomic_task.rs | 12 +- tokio-sync/tests/fuzz_list.rs | 6 +- tokio-sync/tests/fuzz_mpsc.rs | 3 +- tokio-sync/tests/fuzz_oneshot.rs | 8 +- tokio-sync/tests/fuzz_semaphore.rs | 10 +- tokio-sync/tests/lock.rs | 7 +- tokio-sync/tests/mpsc.rs | 13 +- tokio-sync/tests/oneshot.rs | 10 +- tokio-sync/tests/semaphore.rs | 7 +- tokio-sync/tests/watch.rs | 5 +- tokio-tcp/Cargo.toml | 12 +- tokio-tcp/src/incoming.rs | 3 +- tokio-tcp/src/lib.rs | 12 +- tokio-tcp/src/listener.rs | 82 ++--- tokio-tcp/src/stream.rs | 163 +++------ tokio-tcp/tests/chain.rs | 11 +- tokio-tcp/tests/echo.rs | 11 +- tokio-tcp/tests/limit.rs | 11 +- tokio-tcp/tests/stream-buffered.rs | 11 +- tokio-tcp/tests/tcp.rs | 10 +- tokio-test/Cargo.toml | 9 +- tokio-test/README.md | 1 - tokio-test/src/clock.rs | 13 +- tokio-test/src/lib.rs | 16 +- tokio-test/src/task.rs | 4 +- tokio-test/tests/clock.rs | 6 +- tokio-threadpool/Cargo.toml | 8 +- tokio-threadpool/README.md | 3 - tokio-threadpool/benches/basic.rs | 8 +- tokio-threadpool/benches/blocking.rs | 16 +- tokio-threadpool/benches/depth.rs | 8 +- tokio-threadpool/src/blocking.rs | 13 +- tokio-threadpool/src/builder.rs | 105 ++---- tokio-threadpool/src/callback.rs | 8 +- tokio-threadpool/src/config.rs | 11 +- tokio-threadpool/src/lib.rs | 30 +- tokio-threadpool/src/notifier.rs | 9 +- tokio-threadpool/src/park/boxed.rs | 8 +- tokio-threadpool/src/park/default_park.rs | 8 +- tokio-threadpool/src/pool/backup.rs | 6 +- tokio-threadpool/src/pool/backup_stack.rs | 2 +- tokio-threadpool/src/pool/mod.rs | 24 +- tokio-threadpool/src/pool/state.rs | 2 +- tokio-threadpool/src/sender.rs | 15 +- tokio-threadpool/src/shutdown.rs | 6 +- tokio-threadpool/src/task/blocking.rs | 10 +- tokio-threadpool/src/task/blocking_state.rs | 5 +- tokio-threadpool/src/task/mod.rs | 12 +- tokio-threadpool/src/thread_pool.rs | 18 +- tokio-threadpool/src/worker/entry.rs | 22 +- tokio-threadpool/src/worker/mod.rs | 20 +- tokio-threadpool/src/worker/stack.rs | 7 +- tokio-threadpool/src/worker/state.rs | 2 +- tokio-threadpool/tests/blocking.rs | 10 +- tokio-threadpool/tests/hammer.rs | 7 +- tokio-threadpool/tests/threadpool.rs | 25 +- tokio-timer/Cargo.toml | 10 +- tokio-timer/src/clock/clock.rs | 12 +- tokio-timer/src/deadline.rs | 12 +- tokio-timer/src/delay.rs | 6 +- tokio-timer/src/delay_queue.rs | 61 ++-- tokio-timer/src/error.rs | 3 +- tokio-timer/src/interval.rs | 11 +- tokio-timer/src/lib.rs | 25 +- tokio-timer/src/throttle.rs | 10 +- tokio-timer/src/timeout.rs | 22 +- tokio-timer/src/timer/atomic_stack.rs | 3 +- tokio-timer/src/timer/entry.rs | 8 +- tokio-timer/src/timer/handle.rs | 10 +- tokio-timer/src/timer/mod.rs | 22 +- tokio-timer/src/timer/now.rs | 2 +- tokio-timer/src/timer/registration.rs | 8 +- tokio-timer/src/timer/stack.rs | 3 +- tokio-timer/src/wheel/level.rs | 5 +- tokio-timer/tests/clock.rs | 9 +- tokio-timer/tests/deadline.rs | 10 +- tokio-timer/tests/delay.rs | 13 +- tokio-timer/tests/hammer.rs | 12 +- tokio-timer/tests/interval.rs | 10 +- tokio-timer/tests/queue.rs | 15 +- tokio-timer/tests/support/mod.rs | 4 + tokio-timer/tests/throttle.rs | 7 +- tokio-timer/tests/timeout.rs | 10 +- tokio-tls/Cargo.toml | 10 +- tokio-tls/README.md | 3 - tokio-tls/examples/download-rust-lang.rs | 15 +- tokio-tls/examples/echo.rs | 11 +- tokio-tls/src/lib.rs | 14 +- tokio-tls/tests/bad.rs | 27 +- tokio-tls/tests/google.rs | 23 +- tokio-tls/tests/smoke.rs | 32 +- tokio-udp/Cargo.toml | 12 +- tokio-udp/src/frame.rs | 10 +- tokio-udp/src/lib.rs | 14 +- tokio-udp/src/recv_dgram.rs | 19 +- tokio-udp/src/send_dgram.rs | 4 +- tokio-udp/src/socket.rs | 9 +- tokio-udp/tests/udp.rs | 26 +- tokio-uds/Cargo.toml | 14 +- tokio-uds/src/datagram.rs | 11 +- tokio-uds/src/frame.rs | 10 +- tokio-uds/src/incoming.rs | 6 +- tokio-uds/src/lib.rs | 33 +- tokio-uds/src/listener.rs | 11 +- tokio-uds/src/recv_dgram.rs | 6 +- tokio-uds/src/send_dgram.rs | 6 +- tokio-uds/src/stream.rs | 11 +- tokio-uds/src/ucred.rs | 9 +- tokio-uds/tests/datagram.rs | 20 +- tokio-uds/tests/stream.rs | 15 +- tokio/Cargo.toml | 33 +- tokio/README.md | 2 - {benches => tokio/benches}/latency.rs | 6 +- {benches => tokio/benches}/mio-ops.rs | 3 +- {benches => tokio/benches}/tcp.rs | 17 +- tokio/examples/blocking.rs | 4 +- .../chat-combinator-current-thread.rs | 17 +- tokio/examples/chat-combinator.rs | 16 +- tokio/examples/chat.rs | 18 +- tokio/examples/connect.rs | 25 +- tokio/examples/echo-udp.rs | 11 +- tokio/examples/echo.rs | 12 +- tokio/examples/hello_world.rs | 7 +- tokio/examples/manual-runtime.rs | 18 +- tokio/examples/print_each_packet.rs | 13 +- tokio/examples/proxy.rs | 8 +- tokio/examples/tinydb.rs | 8 +- tokio/examples/tinyhttp.rs | 33 +- tokio/examples/udp-client.rs | 7 +- tokio/examples/udp-codec.rs | 12 +- tokio/src/async_await.rs | 4 +- tokio/src/codec/length_delimited.rs | 39 +- tokio/src/codec/mod.rs | 7 +- tokio/src/executor/current_thread/mod.rs | 6 +- tokio/src/executor/mod.rs | 4 +- tokio/src/lib.rs | 53 +-- tokio/src/prelude.rs | 12 +- tokio/src/reactor/mod.rs | 9 +- tokio/src/reactor/poll_evented.rs | 12 +- .../src/runtime/current_thread/async_await.rs | 2 +- tokio/src/runtime/current_thread/builder.rs | 9 +- tokio/src/runtime/current_thread/mod.rs | 2 - tokio/src/runtime/current_thread/runtime.rs | 21 +- tokio/src/runtime/mod.rs | 9 +- tokio/src/runtime/threadpool/async_await.rs | 2 +- tokio/src/runtime/threadpool/builder.rs | 37 +- tokio/src/runtime/threadpool/mod.rs | 19 +- tokio/src/runtime/threadpool/shutdown.rs | 8 +- tokio/src/runtime/threadpool/task_executor.rs | 18 +- tokio/src/timer.rs | 6 +- tokio/src/util/enumerate.rs | 2 +- tokio/src/util/future.rs | 9 +- tokio/src/util/stream.rs | 9 +- tokio/tests/buffered.rs | 11 +- tokio/tests/clock.rs | 12 +- tokio/tests/drop-core.rs | 8 +- tokio/tests/enumerate.rs | 5 +- tokio/tests/global.rs | 11 +- tokio/tests/length_delimited.rs | 10 +- tokio/tests/line-frames.rs | 14 +- tokio/tests/pipe-hup.rs | 20 +- tokio/tests/reactor.rs | 17 +- tokio/tests/runtime.rs | 28 +- tokio/tests/timer.rs | 12 +- 343 files changed, 1725 insertions(+), 2813 deletions(-) rename tokio-futures/src/{await.rs => async_wait.rs} (84%) rename {benches => tokio/benches}/latency.rs (97%) rename {benches => tokio/benches}/mio-ops.rs (97%) rename {benches => tokio/benches}/tcp.rs (97%) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 580be1a40..da207a2ba 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -153,8 +153,6 @@ The type level example for `tokio_timer::Timeout` provides a good example of a documentation test: ``` -/// # extern crate futures; -/// # extern crate tokio; /// // import the `timeout` function, usually this is done /// // with `use tokio::prelude::*` /// use tokio::prelude::FutureExt; @@ -192,8 +190,6 @@ If this were a documentation test for the `Timeout::new` function, then the example would explicitly use `Timeout::new`. For example: ``` -/// # extern crate futures; -/// # extern crate tokio; /// use tokio::timer::Timeout; /// use futures::Future; /// use futures::sync::oneshot; diff --git a/README.md b/README.md index 9aff68374..20f5bf189 100644 --- a/README.md +++ b/README.md @@ -58,8 +58,6 @@ an asynchronous application. A basic TCP echo server with Tokio: ```rust -extern crate tokio; - use tokio::prelude::*; use tokio::io::copy; use tokio::net::TcpListener; diff --git a/async-await/Cargo.toml b/async-await/Cargo.toml index e605da602..52933b28d 100644 --- a/async-await/Cargo.toml +++ b/async-await/Cargo.toml @@ -25,25 +25,7 @@ name = "hyper" path = "src/hyper.rs" [dependencies] -tokio = { version = "0.1.18", features = ["async-await-preview"] } +tokio = { version = "0.2.0", features = ["async-await-preview"], path = "../tokio" } futures = "0.1.23" bytes = "0.4.9" hyper = "0.12.8" - -# Avoid using crates.io for Tokio dependencies -[patch.crates-io] -tokio = { path = "../tokio" } -tokio-codec = { path = "../tokio-codec" } -tokio-current-thread = { path = "../tokio-current-thread" } -tokio-executor = { path = "../tokio-executor" } -tokio-fs = { path = "../tokio-fs" } -tokio-futures = { path = "../tokio-futures" } -tokio-io = { path = "../tokio-io" } -tokio-reactor = { path = "../tokio-reactor" } -tokio-signal = { path = "../tokio-signal" } -tokio-tcp = { path = "../tokio-tcp" } -tokio-threadpool = { path = "../tokio-threadpool" } -tokio-timer = { path = "../tokio-timer" } -tokio-tls = { path = "../tokio-tls" } -tokio-udp = { path = "../tokio-udp" } -tokio-uds = { path = "../tokio-uds" } diff --git a/async-await/src/chat.rs b/async-await/src/chat.rs index d0576f529..d3a0c9928 100644 --- a/async-await/src/chat.rs +++ b/async-await/src/chat.rs @@ -1,6 +1,6 @@ #![feature(await_macro, async_await)] -use tokio::await; +use tokio::async_wait; use tokio::codec::{LinesCodec, Decoder}; use tokio::net::{TcpListener, TcpStream}; use tokio::prelude::*; @@ -33,7 +33,7 @@ async fn process(stream: TcpStream, state: Arc>) -> io::Result<()> let mut lines = LinesCodec::new().framed(stream); // Extract the peer's name - let name = match await!(lines.next()) { + let name = match async_wait!(lines.next()) { Some(name) => name?, None => { // Disconnected early @@ -56,15 +56,15 @@ async fn process(stream: TcpStream, state: Arc>) -> io::Result<()> // Spawn a task that receives all lines broadcasted to us from other peers // and writes it to the client. tokio::spawn_async(async move { - while let Some(line) = await!(rx.next()) { + while let Some(line) = async_wait!(rx.next()) { let line = line.unwrap(); - await!(lines_tx.send_async(line)).unwrap(); + async_wait!(lines_tx.send_async(line)).unwrap(); } }); // Use the current task to read lines from the socket and broadcast them to // other peers. - while let Some(message) = await!(lines_rx.next()) { + while let Some(message) = async_wait!(lines_rx.next()) { // TODO: Error handling let message = message.unwrap(); @@ -113,7 +113,7 @@ async fn main() { // Start the Tokio runtime. let mut incoming = listener.incoming(); - while let Some(stream) = await!(incoming.next()) { + while let Some(stream) = async_wait!(incoming.next()) { let stream = match stream { Ok(stream) => stream, Err(_) => continue, @@ -122,7 +122,7 @@ async fn main() { let state = state.clone(); tokio::spawn_async(async move { - if let Err(_) = await!(process(stream, state)) { + if let Err(_) = async_wait!(process(stream, state)) { eprintln!("failed to process connection"); } }); diff --git a/async-await/src/echo_client.rs b/async-await/src/echo_client.rs index 7cab4932e..302b7ea22 100644 --- a/async-await/src/echo_client.rs +++ b/async-await/src/echo_client.rs @@ -1,6 +1,6 @@ #![feature(await_macro, async_await)] -use tokio::await; +use tokio::async_wait; use tokio::net::TcpStream; use tokio::prelude::*; @@ -14,7 +14,7 @@ const MESSAGES: &[&str] = &[ ]; async fn run_client(addr: &SocketAddr) -> io::Result<()> { - let mut stream = await!(TcpStream::connect(addr))?; + let mut stream = async_wait!(TcpStream::connect(addr))?; // Buffer to read into let mut buf = [0; 128]; @@ -23,10 +23,10 @@ async fn run_client(addr: &SocketAddr) -> io::Result<()> { println!(" > write = {:?}", msg); // Write the message to the server - await!(stream.write_all_async(msg.as_bytes()))?; + async_wait!(stream.write_all_async(msg.as_bytes()))?; // Read the message back from the server - await!(stream.read_exact_async(&mut buf[..msg.len()]))?; + async_wait!(stream.read_exact_async(&mut buf[..msg.len()]))?; assert_eq!(&buf[..msg.len()], msg.as_bytes()); } @@ -43,7 +43,7 @@ async fn main() { // Connect to the echo serveer - match await!(run_client(&addr)) { + match async_wait!(run_client(&addr)) { Ok(_) => println!("done."), Err(e) => eprintln!("echo client failed; error = {:?}", e), } diff --git a/async-await/src/echo_server.rs b/async-await/src/echo_server.rs index d282ad6bc..63e10e31a 100644 --- a/async-await/src/echo_server.rs +++ b/async-await/src/echo_server.rs @@ -1,6 +1,6 @@ #![feature(await_macro, async_await)] -use tokio::await; +use tokio::async_wait; use tokio::net::{TcpListener, TcpStream}; use tokio::prelude::*; @@ -11,11 +11,11 @@ fn handle(mut stream: TcpStream) { let mut buf = [0; 1024]; loop { - match await!(stream.read_async(&mut buf)).unwrap() { + match async_wait!(stream.read_async(&mut buf)).unwrap() { 0 => break, // Socket closed n => { // Send the data back - await!(stream.write_all_async(&buf[0..n])).unwrap(); + async_wait!(stream.write_all_async(&buf[0..n])).unwrap(); } } } @@ -35,7 +35,7 @@ async fn main() { let mut incoming = listener.incoming(); - while let Some(stream) = await!(incoming.next()) { + while let Some(stream) = async_wait!(incoming.next()) { let stream = stream.unwrap(); handle(stream); } diff --git a/async-await/src/hyper.rs b/async-await/src/hyper.rs index c86481b43..37332ee40 100644 --- a/async-await/src/hyper.rs +++ b/async-await/src/hyper.rs @@ -1,6 +1,6 @@ #![feature(await_macro, async_await)] -use tokio::await; +use tokio::async_wait; use tokio::prelude::*; use hyper::Client; @@ -13,7 +13,7 @@ async fn main() { let uri = "http://httpbin.org/ip".parse().unwrap(); - let response = await!({ + let response = async_wait!({ client.get(uri) .timeout(Duration::from_secs(10)) }).unwrap(); @@ -22,7 +22,7 @@ async fn main() { let mut body = response.into_body(); - while let Some(chunk) = await!(body.next()) { + while let Some(chunk) = async_wait!(body.next()) { let chunk = chunk.unwrap(); println!("chunk = {}", str::from_utf8(&chunk[..]).unwrap()); } diff --git a/async-await/tests/macros.rs b/async-await/tests/macros.rs index 285e5538a..1fcbf77bc 100644 --- a/async-await/tests/macros.rs +++ b/async-await/tests/macros.rs @@ -1,6 +1,6 @@ #![feature(await_macro, async_await)] -use tokio::await; +use tokio::async_wait; use tokio::timer::Delay; use std::time::{Duration, Instant}; @@ -18,5 +18,5 @@ async fn fail_no_async() { #[tokio::test] async fn use_timer() { let when = Instant::now() + Duration::from_millis(10); - await!(Delay::new(when)); + async_wait!(Delay::new(when)); } diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 3be914e23..1ad71db8a 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -1,6 +1,9 @@ trigger: ["master"] pr: ["master"] +variables: + nightly: nightly-2019-05-09 + jobs: # Check formatting - template: ci/azure-rustfmt.yml @@ -76,7 +79,7 @@ jobs: parameters: name: test_nightly displayName: Test Async / Await - rust: nightly-2019-04-25 + rust: $(nightly) # Try cross compiling - template: ci/azure-cross-compile.yml @@ -94,11 +97,12 @@ jobs: - template: ci/azure-check-minrust.yml parameters: name: minrust - rust_version: 1.26.0 + rust_version: 1.34.0 - template: ci/azure-tsan.yml parameters: name: tsan + rust: $(nightly) - template: ci/azure-deploy-docs.yml parameters: diff --git a/ci/azure-tsan.yml b/ci/azure-tsan.yml index 519960f33..3666c285c 100644 --- a/ci/azure-tsan.yml +++ b/ci/azure-tsan.yml @@ -12,7 +12,7 @@ jobs: steps: - template: azure-install-rust.yml parameters: - rust_version: nightly-2018-11-18 + rust_version: ${{ parameters.rust }} - template: azure-patch-crates.yml - script: | diff --git a/ci/tsan b/ci/tsan index a261830fb..3791c2703 100644 --- a/ci/tsan +++ b/ci/tsan @@ -8,6 +8,8 @@ race:Weak*drop # `std` mpsc is not used in any Tokio code base. This race is triggered by some # rust runtime logic. race:std*mpsc_queue +race:std*lang_start +race:drop*std::thread* # Probably more fences in std. race:__call_tls_dtors diff --git a/tokio-buf/Cargo.toml b/tokio-buf/Cargo.toml index 2fbe81d2e..f9f069abd 100644 --- a/tokio-buf/Cargo.toml +++ b/tokio-buf/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-buf" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.1.x" git tag. -version = "0.1.1" +# - Create "v0.2.x" git tag. +version = "0.2.0" +edition = "2018" authors = ["Carl Lerche "] license = "MIT" repository = "https://github.com/tokio-rs/tokio" @@ -18,6 +19,7 @@ description = """ Asynchronous stream of byte buffers """ categories = ["asynchronous"] +publish = false [dependencies] bytes = "0.4.10" diff --git a/tokio-buf/README.md b/tokio-buf/README.md index d9f3e5e33..f5d939df5 100644 --- a/tokio-buf/README.md +++ b/tokio-buf/README.md @@ -6,19 +6,13 @@ Asynchronous stream of byte buffers ## Usage -First, add this to your `Cargo.toml`: +Add this to your `Cargo.toml`: ```toml [dependencies] tokio-buf = "0.1.1" ``` -Next, add this to your crate: - -```rust -extern crate tokio_buf; -``` - You can find extensive documentation and examples about how to use this crate online at [https://tokio.rs](https://tokio.rs). The [API documentation](https://docs.rs/tokio-buf) is also a great place to get started diff --git a/tokio-buf/src/lib.rs b/tokio-buf/src/lib.rs index c07e40258..823bad49b 100644 --- a/tokio-buf/src/lib.rs +++ b/tokio-buf/src/lib.rs @@ -1,6 +1,12 @@ #![doc(html_root_url = "https://docs.rs/tokio-buf/0.1.1")] -#![deny(missing_docs, missing_debug_implementations, unreachable_pub)] +#![deny( + missing_docs, + missing_debug_implementations, + unreachable_pub, + rust_2018_idioms +)] #![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! Asynchronous stream of bytes. //! @@ -9,13 +15,6 @@ //! instead of yielding arbitrary values, it only yields types that implement //! `Buf` (i.e, byte collections). -extern crate bytes; -#[cfg(feature = "util")] -extern crate either; -#[allow(unused)] -#[macro_use] -extern crate futures; - mod never; mod size_hint; mod str; @@ -26,7 +25,7 @@ pub mod util; pub use self::size_hint::SizeHint; #[doc(inline)] #[cfg(feature = "util")] -pub use util::BufStreamExt; +pub use crate::util::BufStreamExt; use bytes::Buf; use futures::Poll; diff --git a/tokio-buf/src/never.rs b/tokio-buf/src/never.rs index dcbde39c5..e972167be 100644 --- a/tokio-buf/src/never.rs +++ b/tokio-buf/src/never.rs @@ -4,13 +4,13 @@ use std::{error, fmt}; pub enum Never {} impl fmt::Debug for Never { - fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self {} } } impl fmt::Display for Never { - fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self {} } } diff --git a/tokio-buf/src/str.rs b/tokio-buf/src/str.rs index 8af76950c..05327be87 100644 --- a/tokio-buf/src/str.rs +++ b/tokio-buf/src/str.rs @@ -1,6 +1,6 @@ -use never::Never; -use BufStream; -use SizeHint; +use crate::never::Never; +use crate::BufStream; +use crate::SizeHint; use futures::Poll; diff --git a/tokio-buf/src/u8.rs b/tokio-buf/src/u8.rs index 4b1bc58ea..5baf9d8ef 100644 --- a/tokio-buf/src/u8.rs +++ b/tokio-buf/src/u8.rs @@ -1,8 +1,8 @@ +use crate::never::Never; +use crate::BufStream; use bytes::{Bytes, BytesMut}; use futures::Poll; -use never::Never; use std::io; -use BufStream; impl BufStream for Vec { type Item = io::Cursor>; diff --git a/tokio-buf/src/util/chain.rs b/tokio-buf/src/util/chain.rs index 44fc40088..58e17ca50 100644 --- a/tokio-buf/src/util/chain.rs +++ b/tokio-buf/src/util/chain.rs @@ -1,7 +1,7 @@ -use BufStream; +use crate::BufStream; use either::Either; -use futures::Poll; +use futures::{try_ready, Poll}; /// A buf stream that sequences two buf streams together. /// diff --git a/tokio-buf/src/util/collect.rs b/tokio-buf/src/util/collect.rs index d4bc57e6c..5ed0462c0 100644 --- a/tokio-buf/src/util/collect.rs +++ b/tokio-buf/src/util/collect.rs @@ -1,7 +1,7 @@ use super::FromBufStream; -use BufStream; +use crate::BufStream; -use futures::{Future, Poll}; +use futures::{try_ready, Future, Poll}; /// Consumes a buf stream, collecting the data into a single byte container. /// diff --git a/tokio-buf/src/util/from.rs b/tokio-buf/src/util/from.rs index debebb160..05f047be0 100644 --- a/tokio-buf/src/util/from.rs +++ b/tokio-buf/src/util/from.rs @@ -1,4 +1,4 @@ -use SizeHint; +use crate::SizeHint; use bytes::{Buf, BufMut, Bytes}; @@ -138,7 +138,7 @@ impl FromBufStream for Bytes { } impl fmt::Display for CollectVecError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "BufStream is too big") } } @@ -150,7 +150,7 @@ impl Error for CollectVecError { } impl fmt::Display for CollectBytesError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "BufStream too big") } } diff --git a/tokio-buf/src/util/iter.rs b/tokio-buf/src/util/iter.rs index 0f48546af..dff4d343a 100644 --- a/tokio-buf/src/util/iter.rs +++ b/tokio-buf/src/util/iter.rs @@ -1,8 +1,8 @@ +use crate::BufStream; use bytes::Buf; use futures::Poll; use std::error::Error; use std::fmt; -use BufStream; /// Converts an `Iterator` into a `BufStream` which is always ready to yield the /// next value. @@ -42,7 +42,7 @@ where } impl fmt::Display for Never { - fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { unreachable!(); } } diff --git a/tokio-buf/src/util/limit.rs b/tokio-buf/src/util/limit.rs index c89e687ad..03c0d9138 100644 --- a/tokio-buf/src/util/limit.rs +++ b/tokio-buf/src/util/limit.rs @@ -1,4 +1,4 @@ -use BufStream; +use crate::BufStream; use bytes::Buf; use futures::Poll; diff --git a/tokio-buf/src/util/mod.rs b/tokio-buf/src/util/mod.rs index 14c631831..d6848e885 100644 --- a/tokio-buf/src/util/mod.rs +++ b/tokio-buf/src/util/mod.rs @@ -22,7 +22,7 @@ pub mod error { pub use super::limit::LimitError; } -use BufStream; +use crate::BufStream; impl BufStreamExt for T where T: BufStream {} diff --git a/tokio-buf/src/util/stream.rs b/tokio-buf/src/util/stream.rs index 8716f23b8..25af75b38 100644 --- a/tokio-buf/src/util/stream.rs +++ b/tokio-buf/src/util/stream.rs @@ -1,6 +1,6 @@ +use crate::BufStream; use bytes::Buf; use futures::{Async, Poll, Stream}; -use BufStream; /// Converts a `Stream` of `Buf` types into a `BufStream`. /// diff --git a/tokio-buf/tests/buf_stream.rs b/tokio-buf/tests/buf_stream.rs index 35a3f938d..a31826f07 100644 --- a/tokio-buf/tests/buf_stream.rs +++ b/tokio-buf/tests/buf_stream.rs @@ -1,7 +1,5 @@ -extern crate tokio_buf; - use tokio_buf::BufStream; // Ensures that `BufStream` can be a trait object #[allow(dead_code)] -fn obj(_: &mut BufStream) {} +fn obj(_: &mut dyn BufStream) {} diff --git a/tokio-buf/tests/chain.rs b/tokio-buf/tests/chain.rs index 7cc7ea701..798dd96cc 100644 --- a/tokio-buf/tests/chain.rs +++ b/tokio-buf/tests/chain.rs @@ -1,15 +1,9 @@ #![cfg(feature = "util")] -extern crate bytes; -extern crate futures; -extern crate tokio_buf; - use futures::Async::*; use tokio_buf::{BufStream, BufStreamExt}; -#[macro_use] mod support; - use support::*; #[test] diff --git a/tokio-buf/tests/collect.rs b/tokio-buf/tests/collect.rs index dd367c2d1..f9bb401cc 100644 --- a/tokio-buf/tests/collect.rs +++ b/tokio-buf/tests/collect.rs @@ -1,16 +1,10 @@ #![cfg(feature = "util")] -extern crate bytes; -extern crate futures; -extern crate tokio_buf; - use bytes::Bytes; use futures::Future; use tokio_buf::BufStreamExt; -#[macro_use] mod support; - use support::*; macro_rules! test_collect_impl { diff --git a/tokio-buf/tests/iter.rs b/tokio-buf/tests/iter.rs index 365a396ec..464ff4613 100644 --- a/tokio-buf/tests/iter.rs +++ b/tokio-buf/tests/iter.rs @@ -1,12 +1,7 @@ -extern crate bytes; -extern crate futures; -extern crate tokio_buf; - use futures::Async::*; use std::io::Cursor; use tokio_buf::{util, BufStream}; -#[macro_use] mod support; type Buf = Cursor<&'static [u8]>; diff --git a/tokio-buf/tests/limit.rs b/tokio-buf/tests/limit.rs index 1cd909219..d08a90830 100644 --- a/tokio-buf/tests/limit.rs +++ b/tokio-buf/tests/limit.rs @@ -1,16 +1,10 @@ #![cfg(feature = "util")] -extern crate bytes; -extern crate futures; -extern crate tokio_buf; - use futures::Async::*; use futures::Future; use tokio_buf::{BufStream, BufStreamExt}; -#[macro_use] mod support; - use support::*; #[test] diff --git a/tokio-buf/tests/size_hint.rs b/tokio-buf/tests/size_hint.rs index 45f867655..467a4a2d1 100644 --- a/tokio-buf/tests/size_hint.rs +++ b/tokio-buf/tests/size_hint.rs @@ -1,5 +1,3 @@ -extern crate tokio_buf; - use tokio_buf::SizeHint; #[test] diff --git a/tokio-buf/tests/stream.rs b/tokio-buf/tests/stream.rs index 3491feb49..c7a394fc5 100644 --- a/tokio-buf/tests/stream.rs +++ b/tokio-buf/tests/stream.rs @@ -1,15 +1,9 @@ -extern crate bytes; -extern crate futures; -extern crate tokio_buf; -extern crate tokio_mock_task; - use futures::sync::mpsc; use futures::Async::*; use std::io::Cursor; use tokio_buf::{util, BufStream}; use tokio_mock_task::MockTask; -#[macro_use] mod support; type Buf = Cursor<&'static [u8]>; diff --git a/tokio-buf/tests/string.rs b/tokio-buf/tests/string.rs index a99db2097..754a4a7ef 100644 --- a/tokio-buf/tests/string.rs +++ b/tokio-buf/tests/string.rs @@ -1,12 +1,7 @@ -extern crate bytes; -extern crate futures; -extern crate tokio_buf; - use futures::Async::*; use std::fmt; use tokio_buf::BufStream; -#[macro_use] mod support; fn test_hello_world(mut bs: B) diff --git a/tokio-buf/tests/support.rs b/tokio-buf/tests/support.rs index c8d7abfc6..a5e0f0b7d 100644 --- a/tokio-buf/tests/support.rs +++ b/tokio-buf/tests/support.rs @@ -1,9 +1,5 @@ #![allow(unused)] -extern crate bytes; -extern crate futures; -extern crate tokio_buf; - use bytes::Buf; use futures::Async::*; use futures::Poll; @@ -12,6 +8,7 @@ use tokio_buf::{BufStream, SizeHint}; use std::collections::VecDeque; use std::io::Cursor; +#[macro_export] macro_rules! assert_buf_eq { ($actual:expr, $expect:expr) => {{ use bytes::Buf; @@ -27,6 +24,7 @@ macro_rules! assert_buf_eq { }}; } +#[macro_export] macro_rules! assert_none { ($actual:expr) => { match $actual { @@ -36,6 +34,7 @@ macro_rules! assert_none { }; } +#[macro_export] macro_rules! assert_not_ready { ($actual:expr) => { match $actual { diff --git a/tokio-codec/Cargo.toml b/tokio-codec/Cargo.toml index b6dbbdf69..bbc29c334 100644 --- a/tokio-codec/Cargo.toml +++ b/tokio-codec/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-codec" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.1.x" git tag. -version = "0.1.1" +# - Create "v0.2.x" git tag. +version = "0.2.0" +edition = "2018" authors = ["Carl Lerche ", "Bryan Burgers "] license = "MIT" repository = "https://github.com/tokio-rs/tokio" @@ -18,8 +19,9 @@ description = """ Utilities for encoding and decoding frames. """ categories = ["asynchronous"] +publish = false [dependencies] -tokio-io = "0.1.7" +tokio-io = { version = "0.2.0", path = "../tokio-io" } bytes = "0.4.7" futures = "0.1.18" diff --git a/tokio-codec/README.md b/tokio-codec/README.md index e0c1a3858..4c0bf890d 100644 --- a/tokio-codec/README.md +++ b/tokio-codec/README.md @@ -4,21 +4,6 @@ Utilities for encoding and decoding frames. [Documentation](https://docs.rs/tokio-codec) -## Usage - -First, add this to your `Cargo.toml`: - -```toml -[dependencies] -tokio-codec = "0.1" -``` - -Next, add this to your crate: - -```rust -extern crate tokio_codec; -``` - You can find extensive documentation and examples about how to use this crate online at [https://tokio.rs](https://tokio.rs). The [API documentation](https://docs.rs/tokio-codec) is also a great place to get started diff --git a/tokio-codec/src/lib.rs b/tokio-codec/src/lib.rs index a5ed45d06..1e22feb48 100644 --- a/tokio-codec/src/lib.rs +++ b/tokio-codec/src/lib.rs @@ -1,5 +1,7 @@ -#![deny(missing_docs, missing_debug_implementations, warnings)] #![doc(html_root_url = "https://docs.rs/tokio-codec/0.1.1")] +#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! Utilities for encoding and decoding frames. //! @@ -13,13 +15,9 @@ //! [`Stream`]: # //! [transports]: # -extern crate bytes; -extern crate tokio_io; - mod bytes_codec; mod lines_codec; +pub use crate::bytes_codec::BytesCodec; +pub use crate::lines_codec::LinesCodec; pub use tokio_io::_tokio_codec::{Decoder, Encoder, Framed, FramedParts, FramedRead, FramedWrite}; - -pub use bytes_codec::BytesCodec; -pub use lines_codec::LinesCodec; diff --git a/tokio-codec/tests/codecs.rs b/tokio-codec/tests/codecs.rs index 0ab5256f8..4256bbabf 100644 --- a/tokio-codec/tests/codecs.rs +++ b/tokio-codec/tests/codecs.rs @@ -1,5 +1,4 @@ -extern crate bytes; -extern crate tokio_codec; +#![deny(warnings, rust_2018_idioms)] use bytes::{BufMut, Bytes, BytesMut}; use tokio_codec::{BytesCodec, Decoder, Encoder, LinesCodec}; diff --git a/tokio-codec/tests/framed.rs b/tokio-codec/tests/framed.rs index 53aafcbc3..b17472ffb 100644 --- a/tokio-codec/tests/framed.rs +++ b/tokio-codec/tests/framed.rs @@ -1,7 +1,4 @@ -extern crate bytes; -extern crate futures; -extern crate tokio_codec; -extern crate tokio_io; +#![deny(warnings, rust_2018_idioms)] use bytes::{Buf, BufMut, BytesMut, IntoBuf}; use futures::{Future, Stream}; diff --git a/tokio-codec/tests/framed_read.rs b/tokio-codec/tests/framed_read.rs index 53ec20388..ee7cc4566 100644 --- a/tokio-codec/tests/framed_read.rs +++ b/tokio-codec/tests/framed_read.rs @@ -1,17 +1,12 @@ -extern crate bytes; -extern crate futures; -extern crate tokio_codec; -extern crate tokio_io; - -use tokio_codec::{Decoder, FramedRead}; -use tokio_io::AsyncRead; +#![deny(warnings, rust_2018_idioms)] use bytes::{Buf, BytesMut, IntoBuf}; use futures::Async::{NotReady, Ready}; use futures::Stream; - use std::collections::VecDeque; use std::io::{self, Read}; +use tokio_codec::{Decoder, FramedRead}; +use tokio_io::AsyncRead; macro_rules! mock { ($($x:expr,)*) => {{ diff --git a/tokio-codec/tests/framed_write.rs b/tokio-codec/tests/framed_write.rs index 9ce392c68..8f7a1c12f 100644 --- a/tokio-codec/tests/framed_write.rs +++ b/tokio-codec/tests/framed_write.rs @@ -1,16 +1,11 @@ -extern crate bytes; -extern crate futures; -extern crate tokio_codec; -extern crate tokio_io; - -use tokio_codec::{Encoder, FramedWrite}; -use tokio_io::AsyncWrite; +#![deny(warnings, rust_2018_idioms)] use bytes::{BufMut, BytesMut}; use futures::{Poll, Sink}; - use std::collections::VecDeque; use std::io::{self, Write}; +use tokio_codec::{Encoder, FramedWrite}; +use tokio_io::AsyncWrite; macro_rules! mock { ($($x:expr,)*) => {{ diff --git a/tokio-current-thread/Cargo.toml b/tokio-current-thread/Cargo.toml index 386cad6db..af54d114e 100644 --- a/tokio-current-thread/Cargo.toml +++ b/tokio-current-thread/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-current-thread" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.1.x" git tag. -version = "0.1.6" +# - Create "v0.2.x" git tag. +version = "0.2.0" +edition = "2018" documentation = "https://docs.rs/tokio-current-thread/0.1.6/tokio_current_thread" repository = "https://github.com/tokio-rs/tokio" homepage = "https://github.com/tokio-rs/tokio" @@ -19,7 +20,8 @@ Single threaded executor which manage many tasks concurrently on the current thr """ keywords = ["futures", "tokio"] categories = ["concurrency", "asynchronous"] +publish = false [dependencies] -tokio-executor = "0.1.7" +tokio-executor = { version = "0.2.0", path = "../tokio-executor" } futures = "0.1.19" diff --git a/tokio-current-thread/src/lib.rs b/tokio-current-thread/src/lib.rs index 8dc3ebd14..a9800d8c8 100644 --- a/tokio-current-thread/src/lib.rs +++ b/tokio-current-thread/src/lib.rs @@ -1,5 +1,7 @@ #![doc(html_root_url = "https://docs.rs/tokio-current-thread/0.1.6")] -#![deny(warnings, missing_docs, missing_debug_implementations)] +#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! A single-threaded executor which executes tasks on the same thread from which //! they are spawned. @@ -25,19 +27,11 @@ //! [`block_on_all`]: fn.block_on_all.html //! [executor module]: https://docs.rs/tokio/0.1/tokio/executor/index.html -extern crate futures; -extern crate tokio_executor; - mod scheduler; -use self::scheduler::Scheduler; - -use tokio_executor::park::{Park, ParkThread, Unpark}; -use tokio_executor::{Enter, SpawnError}; - +use crate::scheduler::Scheduler; use futures::future::{ExecuteError, ExecuteErrorKind, Executor}; use futures::{executor, Async, Future}; - use std::cell::Cell; use std::error::Error; use std::fmt; @@ -45,6 +39,8 @@ use std::rc::Rc; use std::sync::{atomic, mpsc, Arc}; use std::thread; use std::time::{Duration, Instant}; +use tokio_executor::park::{Park, ParkThread, Unpark}; +use tokio_executor::{Enter, SpawnError}; /// Executes tasks on the current thread pub struct CurrentThread { @@ -64,7 +60,7 @@ pub struct CurrentThread { spawn_handle: Handle, /// Receiver for futures spawned from other threads - spawn_receiver: mpsc::Receiver + Send + 'static>>, + spawn_receiver: mpsc::Receiver + Send + 'static>>, /// The thread-local ID assigned to this executor. id: u64, @@ -97,7 +93,7 @@ impl Turn { } /// A `CurrentThread` instance bound to a supplied execution context. -pub struct Entered<'a, P: Park + 'a> { +pub struct Entered<'a, P: Park> { executor: &'a mut CurrentThread

, enter: &'a mut Enter, } @@ -109,7 +105,7 @@ pub struct RunError { } impl fmt::Display for RunError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{}", self.description()) } } @@ -127,7 +123,7 @@ pub struct RunTimeoutError { } impl fmt::Display for RunTimeoutError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{}", self.description()) } } @@ -149,7 +145,7 @@ pub struct TurnError { } impl fmt::Display for TurnError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{}", self.description()) } } @@ -167,7 +163,7 @@ pub struct BlockError { } impl fmt::Display for BlockError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "Block error") } } @@ -179,18 +175,22 @@ impl Error for BlockError { } /// This is mostly split out to make the borrow checker happy. -struct Borrow<'a, U: 'a> { +struct Borrow<'a, U> { id: u64, scheduler: &'a mut Scheduler, num_futures: &'a atomic::AtomicUsize, } trait SpawnLocal { - fn spawn_local(&mut self, future: Box>, already_counted: bool); + fn spawn_local( + &mut self, + future: Box>, + already_counted: bool, + ); } struct CurrentRunner { - spawn: Cell>, + spawn: Cell>, id: Cell>, } @@ -386,7 +386,7 @@ impl CurrentThread

{ &mut self.park } - fn borrow(&mut self) -> Borrow { + fn borrow(&mut self) -> Borrow<'_, P::Unpark> { Borrow { id: self.id, scheduler: &mut self.scheduler, @@ -424,7 +424,7 @@ impl Drop for CurrentThread

{ impl tokio_executor::Executor for CurrentThread { fn spawn( &mut self, - future: Box + Send>, + future: Box + Send>, ) -> Result<(), SpawnError> { self.borrow().spawn_local(future, false); Ok(()) @@ -442,7 +442,7 @@ where } impl fmt::Debug for CurrentThread

{ - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("CurrentThread") .field("scheduler", &self.scheduler) .field( @@ -616,7 +616,7 @@ impl<'a, P: Park> Entered<'a, P> { } impl<'a, P: Park> fmt::Debug for Entered<'a, P> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Entered") .field("executor", &self.executor) .field("enter", &self.enter) @@ -629,7 +629,7 @@ impl<'a, P: Park> fmt::Debug for Entered<'a, P> { /// Handle to spawn a future on the corresponding `CurrentThread` instance #[derive(Clone)] pub struct Handle { - sender: mpsc::Sender + Send + 'static>>, + sender: mpsc::Sender + Send + 'static>>, num_futures: Arc, shut_down: Cell, notify: executor::NotifyHandle, @@ -641,7 +641,7 @@ pub struct Handle { // Manual implementation because the Sender does not implement Debug impl fmt::Debug for Handle { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Handle") .field("shut_down", &self.shut_down.get()) .finish() @@ -731,7 +731,7 @@ impl TaskExecutor { /// Spawn a future onto the current `CurrentThread` instance. pub fn spawn_local( &mut self, - future: Box>, + future: Box>, ) -> Result<(), SpawnError> { CURRENT.with(|current| match current.spawn.get() { Some(spawn) => { @@ -746,7 +746,7 @@ impl TaskExecutor { impl tokio_executor::Executor for TaskExecutor { fn spawn( &mut self, - future: Box + Send>, + future: Box + Send>, ) -> Result<(), SpawnError> { self.spawn_local(future) } @@ -791,7 +791,11 @@ impl<'a, U: Unpark> Borrow<'a, U> { } impl<'a, U: Unpark> SpawnLocal for Borrow<'a, U> { - fn spawn_local(&mut self, future: Box>, already_counted: bool) { + fn spawn_local( + &mut self, + future: Box>, + already_counted: bool, + ) { if !already_counted { // NOTE: we have a borrow of the Runtime, so we know that it isn't shut down. // NOTE: += 2 since LSB is the shutdown bit @@ -804,7 +808,7 @@ impl<'a, U: Unpark> SpawnLocal for Borrow<'a, U> { // ===== impl CurrentRunner ===== impl CurrentRunner { - fn set_spawn(&self, spawn: &mut SpawnLocal, f: F) -> R + fn set_spawn(&self, spawn: &mut dyn SpawnLocal, f: F) -> R where F: FnOnce() -> R, { @@ -819,14 +823,14 @@ impl CurrentRunner { let _reset = Reset(self); - let spawn = unsafe { hide_lt(spawn as *mut SpawnLocal) }; + let spawn = unsafe { hide_lt(spawn as *mut dyn SpawnLocal) }; self.spawn.set(Some(spawn)); f() } } -unsafe fn hide_lt<'a>(p: *mut (SpawnLocal + 'a)) -> *mut (SpawnLocal + 'static) { +unsafe fn hide_lt<'a>(p: *mut (dyn SpawnLocal + 'a)) -> *mut (dyn SpawnLocal + 'static) { use std::mem; mem::transmute(p) } diff --git a/tokio-current-thread/src/scheduler.rs b/tokio-current-thread/src/scheduler.rs index c814b60f7..decef395b 100644 --- a/tokio-current-thread/src/scheduler.rs +++ b/tokio-current-thread/src/scheduler.rs @@ -1,10 +1,6 @@ -use super::Borrow; -use tokio_executor::park::Unpark; -use tokio_executor::Enter; - +use crate::Borrow; use futures::executor::{self, NotifyHandle, Spawn, UnsafeNotify}; use futures::{Async, Future}; - use std::cell::UnsafeCell; use std::fmt::{self, Debug}; use std::marker::PhantomData; @@ -15,6 +11,8 @@ use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize}; use std::sync::{Arc, Weak}; use std::thread; use std::usize; +use tokio_executor::park::Unpark; +use tokio_executor::Enter; /// A generic task-aware scheduler. /// @@ -24,7 +22,7 @@ pub struct Scheduler { nodes: List, } -pub struct Notify<'a, U: 'a>(&'a Arc>); +pub struct Notify<'a, U>(&'a Arc>); // A linked-list of nodes struct List { @@ -125,10 +123,10 @@ enum Dequeue { } /// Wraps a spawned boxed future -struct Task(Spawn>>); +struct Task(Spawn>>); /// A task that is scheduled. `turn` must be called -pub struct Scheduled<'a, U: 'a> { +pub struct Scheduled<'a, U> { task: &'a mut Task, notify: &'a Notify<'a, U>, done: &'a mut bool, @@ -171,7 +169,7 @@ where self.inner.clone().into() } - pub fn schedule(&mut self, item: Box>) { + pub fn schedule(&mut self, item: Box>) { // Get the current scheduler tick let tick_num = self.inner.tick_num.load(SeqCst); @@ -259,7 +257,7 @@ where // assume is is complete (will return Ready or panic), in // which case we'll want to discard it regardless. // - struct Bomb<'a, U: Unpark + 'a> { + struct Bomb<'a, U: Unpark> { borrow: &'a mut Borrow<'a, U>, enter: &'a mut Enter, node: Option>>, @@ -359,13 +357,13 @@ impl<'a, U: Unpark> Scheduled<'a, U> { } impl Task { - pub fn new(future: Box + 'static>) -> Self { + pub fn new(future: Box + 'static>) -> Self { Task(executor::spawn(future)) } } impl fmt::Debug for Task { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Task").finish() } } @@ -399,7 +397,7 @@ fn release_node(node: Arc>) { } impl Debug for Scheduler { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "Scheduler {{ ... }}") } } @@ -639,7 +637,7 @@ impl<'a, U> Clone for Notify<'a, U> { } impl<'a, U> fmt::Debug for Notify<'a, U> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Notify").finish() } } @@ -687,8 +685,8 @@ unsafe impl UnsafeNotify for ArcNode { } } -unsafe fn hide_lt(p: *mut ArcNode) -> *mut UnsafeNotify { - mem::transmute(p as *mut UnsafeNotify) +unsafe fn hide_lt(p: *mut ArcNode) -> *mut dyn UnsafeNotify { + mem::transmute(p as *mut dyn UnsafeNotify) } impl Node { diff --git a/tokio-current-thread/tests/current_thread.rs b/tokio-current-thread/tests/current_thread.rs index 0ed0ca246..7336baf6e 100644 --- a/tokio-current-thread/tests/current_thread.rs +++ b/tokio-current-thread/tests/current_thread.rs @@ -1,28 +1,24 @@ -extern crate futures; -extern crate tokio_current_thread; -extern crate tokio_executor; - -use tokio_current_thread::{block_on_all, CurrentThread}; +#![deny(warnings, rust_2018_idioms)] +use futures::future::{self, lazy}; +// This is not actually unused --- we need this trait to be in scope for +// the tests that sue TaskExecutor::current().execute(). The compiler +// doesn't realise that. +#[allow(unused_imports)] +use futures::future::Executor; +use futures::prelude::*; +use futures::sync::oneshot; +use futures::task; use std::any::Any; use std::cell::{Cell, RefCell}; use std::rc::Rc; use std::thread; use std::time::Duration; - -use futures::future::{self, lazy}; -use futures::task; -// This is not actually unused --- we need this trait to be in scope for -// the tests that sue TaskExecutor::current().execute(). The compiler -// doesn't realise that. -#[allow(unused_imports)] -use futures::future::Executor as _futures_Executor; -use futures::prelude::*; -use futures::sync::oneshot; +use tokio_current_thread::{block_on_all, CurrentThread}; mod from_block_on_all { use super::*; - fn test>) + 'static>(spawn: F) { + fn test>) + 'static>(spawn: F) { let cnt = Rc::new(Cell::new(0)); let c = cnt.clone(); @@ -102,7 +98,7 @@ fn spawn_many() { mod does_not_set_global_executor_by_default { use super::*; - fn test + Send>) -> Result<(), E> + 'static, E>( + fn test + Send>) -> Result<(), E> + 'static, E>( spawn: F, ) { block_on_all(lazy(|| { @@ -127,7 +123,7 @@ mod does_not_set_global_executor_by_default { mod from_block_on_future { use super::*; - fn test>)>(spawn: F) { + fn test>)>(spawn: F) { let cnt = Rc::new(Cell::new(0)); let mut tokio_current_thread = CurrentThread::new(); @@ -181,8 +177,8 @@ mod outstanding_tasks_are_dropped_when_executor_is_dropped { fn test(spawn: F, dotspawn: G) where - F: Fn(Box>) + 'static, - G: Fn(&mut CurrentThread, Box>), + F: Fn(Box>) + 'static, + G: Fn(&mut CurrentThread, Box>), { let mut rc = Rc::new(()); @@ -383,8 +379,8 @@ mod and_turn { fn test(spawn: F, dotspawn: G) where - F: Fn(Box>) + 'static, - G: Fn(&mut CurrentThread, Box>), + F: Fn(Box>) + 'static, + G: Fn(&mut CurrentThread, Box>), { let cnt = Rc::new(Cell::new(0)); let c = cnt.clone(); @@ -459,7 +455,7 @@ mod in_drop { } struct MyFuture { - _data: Box, + _data: Box, } impl Future for MyFuture { @@ -473,8 +469,8 @@ mod in_drop { fn test(spawn: F, dotspawn: G) where - F: Fn(Box>) + 'static, - G: Fn(&mut CurrentThread, Box>), + F: Fn(Box>) + 'static, + G: Fn(&mut CurrentThread, Box>), { let mut tokio_current_thread = CurrentThread::new(); @@ -827,7 +823,7 @@ fn spawn_from_executor_with_handle() { Ok::<_, ()>(()) })); - current_thread.run(); + current_thread.run().unwrap(); rx.wait().unwrap(); } diff --git a/tokio-executor/Cargo.toml b/tokio-executor/Cargo.toml index ed3419042..5f8ae6a42 100644 --- a/tokio-executor/Cargo.toml +++ b/tokio-executor/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-executor" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.1.x" git tag. -version = "0.1.7" +# - Create "v0.2.x" git tag. +version = "0.2.0" +edition = "2018" documentation = "https://docs.rs/tokio-executor/0.1.7/tokio_executor" repository = "https://github.com/tokio-rs/tokio" homepage = "https://github.com/tokio-rs/tokio" @@ -19,10 +20,11 @@ Future execution primitives """ keywords = ["futures", "tokio"] categories = ["concurrency", "asynchronous"] +publish = false [dependencies] crossbeam-utils = "0.6.2" futures = "0.1.19" [dev-dependencies] -tokio = "0.1.18" +tokio = { version = "0.2.0", path = "../tokio" } diff --git a/tokio-executor/src/enter.rs b/tokio-executor/src/enter.rs index 64bfeb340..597d09107 100644 --- a/tokio-executor/src/enter.rs +++ b/tokio-executor/src/enter.rs @@ -1,17 +1,16 @@ +use futures::{self, Future}; use std::cell::Cell; use std::error::Error; use std::fmt; use std::prelude::v1::*; -use futures::{self, Future}; - thread_local!(static ENTERED: Cell = Cell::new(false)); /// Represents an executor context. /// /// For more details, see [`enter` documentation](fn.enter.html) pub struct Enter { - on_exit: Vec>, + on_exit: Vec>, permanent: bool, } @@ -22,7 +21,7 @@ pub struct EnterError { } impl fmt::Debug for EnterError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("EnterError") .field("reason", &self.description()) .finish() @@ -30,7 +29,7 @@ impl fmt::Debug for EnterError { } impl fmt::Display for EnterError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{}", self.description()) } } @@ -94,7 +93,7 @@ impl Enter { } impl fmt::Debug for Enter { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Enter").finish() } } diff --git a/tokio-executor/src/error.rs b/tokio-executor/src/error.rs index 579239f08..bf46bf560 100644 --- a/tokio-executor/src/error.rs +++ b/tokio-executor/src/error.rs @@ -38,7 +38,7 @@ impl SpawnError { } impl fmt::Display for SpawnError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{}", self.description()) } } diff --git a/tokio-executor/src/executor.rs b/tokio-executor/src/executor.rs index 11276d0e8..c0b156f08 100644 --- a/tokio-executor/src/executor.rs +++ b/tokio-executor/src/executor.rs @@ -1,5 +1,5 @@ +use crate::SpawnError; use futures::Future; -use SpawnError; /// A value that executes futures. /// @@ -48,17 +48,15 @@ use SpawnError; /// # Examples /// /// ```rust -/// # extern crate futures; -/// # extern crate tokio_executor; -/// # use tokio_executor::Executor; -/// # fn docs(my_executor: &mut Executor) { +/// use tokio_executor::Executor; /// use futures::future::lazy; +/// +/// # fn docs(my_executor: &mut dyn Executor) { /// my_executor.spawn(Box::new(lazy(|| { /// println!("running on the executor"); /// Ok(()) /// }))).unwrap(); /// # } -/// # fn main() {} /// ``` /// /// [`spawn`]: #tymethod.spawn @@ -80,21 +78,19 @@ pub trait Executor { /// # Examples /// /// ```rust - /// # extern crate futures; - /// # extern crate tokio_executor; - /// # use tokio_executor::Executor; - /// # fn docs(my_executor: &mut Executor) { + /// use tokio_executor::Executor; /// use futures::future::lazy; + /// + /// # fn docs(my_executor: &mut dyn Executor) { /// my_executor.spawn(Box::new(lazy(|| { /// println!("running on the executor"); /// Ok(()) /// }))).unwrap(); /// # } - /// # fn main() {} /// ``` fn spawn( &mut self, - future: Box + Send>, + future: Box + Send>, ) -> Result<(), SpawnError>; /// Provides a best effort **hint** to whether or not `spawn` will succeed. @@ -115,12 +111,10 @@ pub trait Executor { /// # Examples /// /// ```rust - /// # extern crate futures; - /// # extern crate tokio_executor; - /// # use tokio_executor::Executor; - /// # fn docs(my_executor: &mut Executor) { + /// use tokio_executor::Executor; /// use futures::future::lazy; /// + /// # fn docs(my_executor: &mut dyn Executor) { /// if my_executor.status().is_ok() { /// my_executor.spawn(Box::new(lazy(|| { /// println!("running on the executor"); @@ -130,7 +124,6 @@ pub trait Executor { /// println!("the executor is not in a good state"); /// } /// # } - /// # fn main() {} /// ``` fn status(&self) -> Result<(), SpawnError> { Ok(()) @@ -140,7 +133,7 @@ pub trait Executor { impl Executor for Box { fn spawn( &mut self, - future: Box + Send>, + future: Box + Send>, ) -> Result<(), SpawnError> { (**self).spawn(future) } diff --git a/tokio-executor/src/global.rs b/tokio-executor/src/global.rs index 47f7505ca..1c4c53ff8 100644 --- a/tokio-executor/src/global.rs +++ b/tokio-executor/src/global.rs @@ -1,7 +1,5 @@ use super::{Enter, Executor, SpawnError}; - use futures::{future, Future}; - use std::cell::Cell; /// Executes futures on the default executor for the current execution context. @@ -37,7 +35,7 @@ impl DefaultExecutor { } #[inline] - fn with_current R, R>(f: F) -> Option { + fn with_current R, R>(f: F) -> Option { EXECUTOR.with( |current_executor| match current_executor.replace(State::Active) { State::Ready(executor_ptr) => { @@ -57,7 +55,7 @@ enum State { // default executor not defined Empty, // default executor is defined and ready to be used - Ready(*mut Executor), + Ready(*mut dyn Executor), // default executor is currently active (used to detect recursive calls) Active, } @@ -72,7 +70,7 @@ thread_local! { impl super::Executor for DefaultExecutor { fn spawn( &mut self, - future: Box + Send>, + future: Box + Send>, ) -> Result<(), SpawnError> { DefaultExecutor::with_current(|executor| executor.spawn(future)) .unwrap_or_else(|| Err(SpawnError::shutdown())) @@ -144,19 +142,14 @@ where /// /// # Examples /// -/// ```rust -/// # extern crate futures; -/// # extern crate tokio_executor; -/// # use tokio_executor::spawn; -/// # pub fn dox() { +/// ```no_run +/// use tokio_executor::spawn; /// use futures::future::lazy; /// /// spawn(lazy(|| { /// println!("running on the default executor"); /// Ok(()) /// })); -/// # } -/// # pub fn main() {} /// ``` pub fn spawn(future: T) where @@ -210,7 +203,7 @@ where }) } -unsafe fn hide_lt<'a>(p: *mut (Executor + 'a)) -> *mut (Executor + 'static) { +unsafe fn hide_lt<'a>(p: *mut (dyn Executor + 'a)) -> *mut (dyn Executor + 'static) { use std::mem; mem::transmute(p) } diff --git a/tokio-executor/src/lib.rs b/tokio-executor/src/lib.rs index 5362d0fae..4e2d32826 100644 --- a/tokio-executor/src/lib.rs +++ b/tokio-executor/src/lib.rs @@ -1,5 +1,7 @@ -#![deny(missing_docs, missing_debug_implementations, warnings)] #![doc(html_root_url = "https://docs.rs/tokio-executor/0.1.7")] +#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! Task execution related traits and utilities. //! @@ -51,9 +53,6 @@ //! [`Park`]: park/index.html //! [`Future::poll`]: https://docs.rs/futures/0.1/futures/future/trait.Future.html#tymethod.poll -extern crate crossbeam_utils; -extern crate futures; - mod enter; mod error; mod executor; @@ -61,8 +60,8 @@ mod global; pub mod park; mod typed; -pub use enter::{enter, Enter, EnterError}; -pub use error::SpawnError; -pub use executor::Executor; -pub use global::{spawn, with_default, DefaultExecutor}; -pub use typed::TypedExecutor; +pub use crate::enter::{enter, Enter, EnterError}; +pub use crate::error::SpawnError; +pub use crate::executor::Executor; +pub use crate::global::{spawn, with_default, DefaultExecutor}; +pub use crate::typed::TypedExecutor; diff --git a/tokio-executor/src/park.rs b/tokio-executor/src/park.rs index 073c4fef3..b7c4dbf05 100644 --- a/tokio-executor/src/park.rs +++ b/tokio-executor/src/park.rs @@ -44,13 +44,12 @@ //! [up]: trait.Unpark.html //! [mio]: https://docs.rs/mio/0.6/mio/struct.Poll.html +use crossbeam_utils::sync::{Parker, Unparker}; use std::marker::PhantomData; use std::rc::Rc; use std::sync::Arc; use std::time::Duration; -use crossbeam_utils::sync::{Parker, Unparker}; - /// Block the current thread. /// /// See [module documentation][mod] for more details. @@ -128,13 +127,13 @@ pub trait Unpark: Sync + Send + 'static { fn unpark(&self); } -impl Unpark for Box { +impl Unpark for Box { fn unpark(&self) { (**self).unpark() } } -impl Unpark for Arc { +impl Unpark for Arc { fn unpark(&self) { (**self).unpark() } diff --git a/tokio-executor/src/typed.rs b/tokio-executor/src/typed.rs index 22edf29d1..5fd0f272d 100644 --- a/tokio-executor/src/typed.rs +++ b/tokio-executor/src/typed.rs @@ -1,4 +1,4 @@ -use SpawnError; +use crate::SpawnError; /// A value that spawns futures of a specific type. /// @@ -21,11 +21,7 @@ use SpawnError; /// task is spawned. /// /// ```rust -/// #[macro_use] -/// extern crate futures; -/// extern crate tokio; -/// -/// use futures::{Future, Stream, Poll}; +/// use futures::{try_ready, Future, Stream, Poll}; /// use tokio::executor::TypedExecutor; /// use tokio::sync::oneshot; /// @@ -69,7 +65,6 @@ use SpawnError; /// Ok(().into()) /// } /// } -/// # pub fn main() {} /// ``` /// /// By doing this, the `drain` fn can accept a stream that is `!Send` as long as @@ -90,10 +85,8 @@ pub trait TypedExecutor { /// # Examples /// /// ```rust - /// # extern crate futures; - /// # extern crate tokio_executor; - /// # use tokio_executor::TypedExecutor; - /// # use futures::{Future, Poll}; + /// use tokio_executor::TypedExecutor; + /// use futures::{Future, Poll}; /// fn example(my_executor: &mut T) /// where /// T: TypedExecutor, @@ -112,7 +105,6 @@ pub trait TypedExecutor { /// Ok(().into()) /// } /// } - /// # fn main() {} /// ``` fn spawn(&mut self, future: T) -> Result<(), SpawnError>; @@ -134,10 +126,9 @@ pub trait TypedExecutor { /// # Examples /// /// ```rust - /// # extern crate futures; - /// # extern crate tokio_executor; - /// # use tokio_executor::TypedExecutor; - /// # use futures::{Future, Poll}; + /// use tokio_executor::TypedExecutor; + /// use futures::{Future, Poll}; + /// /// fn example(my_executor: &mut T) /// where /// T: TypedExecutor, @@ -160,7 +151,6 @@ pub trait TypedExecutor { /// Ok(().into()) /// } /// } - /// # fn main() {} /// ``` fn status(&self) -> Result<(), SpawnError> { Ok(()) diff --git a/tokio-executor/tests/executor.rs b/tokio-executor/tests/executor.rs index bb0202438..c424df50f 100644 --- a/tokio-executor/tests/executor.rs +++ b/tokio-executor/tests/executor.rs @@ -1,8 +1,7 @@ -extern crate futures; -extern crate tokio_executor; +#![deny(warnings, rust_2018_idioms)] -use futures::{future::lazy, Future}; -use tokio_executor::DefaultExecutor; +use futures::{self, future::lazy, Future}; +use tokio_executor::{self, DefaultExecutor}; mod out_of_executor_context { use super::*; @@ -10,7 +9,7 @@ mod out_of_executor_context { fn test(spawn: F) where - F: Fn(Box + Send>) -> Result<(), E>, + F: Fn(Box + Send>) -> Result<(), E>, { let res = spawn(Box::new(lazy(|| Ok(())))); assert!(res.is_err()); diff --git a/tokio-fs/Cargo.toml b/tokio-fs/Cargo.toml index 46613dd6f..59d2ae57a 100644 --- a/tokio-fs/Cargo.toml +++ b/tokio-fs/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-fs" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.1.x" git tag. -version = "0.1.6" +# - Create "v0.2.x" git tag. +version = "0.2.0" +edition = "2018" authors = ["Carl Lerche "] license = "MIT" readme = "README.md" @@ -20,16 +21,16 @@ Filesystem API for Tokio. """ keywords = ["tokio", "futures", "fs", "file", "async"] categories = ["asynchronous", "network-programming", "filesystem"] +publish = false [dependencies] futures = "0.1.21" -tokio-threadpool = "0.1.3" -tokio-io = "0.1.6" +tokio-threadpool = { version = "0.2.0", path = "../tokio-threadpool" } +tokio-io = { version = "0.2.0", path = "../tokio-io" } [dev-dependencies] rand = "0.6" tempfile = "3" tempdir = "0.3" -tokio-io = "0.1.6" -tokio-codec = "0.1.0" -tokio = "0.1.7" +tokio-codec = { version = "0.2.0", path = "../tokio-codec" } +tokio = { version = "0.2.0", path = "../tokio" } diff --git a/tokio-fs/examples/std-echo.rs b/tokio-fs/examples/std-echo.rs index f7433fba6..58028bb37 100644 --- a/tokio-fs/examples/std-echo.rs +++ b/tokio-fs/examples/std-echo.rs @@ -1,11 +1,6 @@ //! Echo everything received on STDIN to STDOUT. #![deny(deprecated, warnings)] -extern crate futures; -extern crate tokio_codec; -extern crate tokio_fs; -extern crate tokio_threadpool; - use tokio_codec::{FramedRead, FramedWrite, LinesCodec}; use tokio_fs::{stderr, stdin, stdout}; use tokio_threadpool::Builder; @@ -14,7 +9,7 @@ use futures::{Future, Sink, Stream}; use std::io; -pub fn main() -> Result<(), Box> { +pub fn main() -> Result<(), Box> { let pool = Builder::new().pool_size(1).build(); pool.spawn({ diff --git a/tokio-fs/src/create_dir.rs b/tokio-fs/src/create_dir.rs index 7ae71d7f7..a07c1ad52 100644 --- a/tokio-fs/src/create_dir.rs +++ b/tokio-fs/src/create_dir.rs @@ -1,9 +1,8 @@ +use futures::{Future, Poll}; use std::fs; use std::io; use std::path::Path; -use futures::{Future, Poll}; - /// Creates a new, empty directory at the provided path /// /// This is an async version of [`std::fs::create_dir`][std] @@ -39,6 +38,6 @@ where type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::create_dir(&self.path)) + crate::blocking_io(|| fs::create_dir(&self.path)) } } diff --git a/tokio-fs/src/create_dir_all.rs b/tokio-fs/src/create_dir_all.rs index 67b0aaf1a..9f034fa46 100644 --- a/tokio-fs/src/create_dir_all.rs +++ b/tokio-fs/src/create_dir_all.rs @@ -1,9 +1,8 @@ +use futures::{Future, Poll}; use std::fs; use std::io; use std::path::Path; -use futures::{Future, Poll}; - /// Recursively create a directory and all of its parent components if they /// are missing. /// @@ -40,6 +39,6 @@ where type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::create_dir_all(&self.path)) + crate::blocking_io(|| fs::create_dir_all(&self.path)) } } diff --git a/tokio-fs/src/file/clone.rs b/tokio-fs/src/file/clone.rs index 9aaaf0870..1bbb6cc9e 100644 --- a/tokio-fs/src/file/clone.rs +++ b/tokio-fs/src/file/clone.rs @@ -1,7 +1,5 @@ use super::File; - use futures::{Future, Poll}; - use std::io; /// Future returned by `File::try_clone`. diff --git a/tokio-fs/src/file/create.rs b/tokio-fs/src/file/create.rs index e92575ccb..da03779e8 100644 --- a/tokio-fs/src/file/create.rs +++ b/tokio-fs/src/file/create.rs @@ -1,7 +1,5 @@ use super::File; - -use futures::{Future, Poll}; - +use futures::{try_ready, Future, Poll}; use std::fs::File as StdFile; use std::io; use std::path::Path; @@ -29,7 +27,7 @@ where type Error = io::Error; fn poll(&mut self) -> Poll { - let std = try_ready!(::blocking_io(|| StdFile::create(&self.path))); + let std = try_ready!(crate::blocking_io(|| StdFile::create(&self.path))); let file = File::from_std(std); Ok(file.into()) diff --git a/tokio-fs/src/file/metadata.rs b/tokio-fs/src/file/metadata.rs index e6eaf6c85..7a3c5ef91 100644 --- a/tokio-fs/src/file/metadata.rs +++ b/tokio-fs/src/file/metadata.rs @@ -1,7 +1,5 @@ use super::File; - -use futures::{Future, Poll}; - +use futures::{try_ready, Future, Poll}; use std::fs::File as StdFile; use std::fs::Metadata; use std::io; @@ -29,7 +27,7 @@ impl Future for MetadataFuture { type Error = io::Error; fn poll(&mut self) -> Poll { - let metadata = try_ready!(::blocking_io(|| StdFile::metadata(self.std()))); + let metadata = try_ready!(crate::blocking_io(|| StdFile::metadata(self.std()))); let file = self.file.take().expect(POLL_AFTER_RESOLVE); Ok((file, metadata).into()) diff --git a/tokio-fs/src/file/mod.rs b/tokio-fs/src/file/mod.rs index 13601b39b..c51bf5b5f 100644 --- a/tokio-fs/src/file/mod.rs +++ b/tokio-fs/src/file/mod.rs @@ -16,13 +16,11 @@ pub use self::open::OpenFuture; pub use self::open_options::OpenOptions; pub use self::seek::SeekFuture; -use tokio_io::{AsyncRead, AsyncWrite}; - use futures::Poll; - use std::fs::{File as StdFile, Metadata, Permissions}; use std::io::{self, Read, Seek, Write}; use std::path::Path; +use tokio_io::{AsyncRead, AsyncWrite}; /// A reference to an open file on the filesystem. /// @@ -42,39 +40,32 @@ use std::path::Path; /// Create a new file and asynchronously write bytes to it: /// /// ```no_run -/// extern crate tokio; -/// /// use tokio::prelude::{AsyncWrite, Future}; /// -/// fn main() { -/// let task = tokio::fs::File::create("foo.txt") -/// .and_then(|mut file| file.poll_write(b"hello, world!")) -/// .map(|res| { -/// println!("{:?}", res); -/// }).map_err(|err| eprintln!("IO error: {:?}", err)); +/// let task = tokio::fs::File::create("foo.txt") +/// .and_then(|mut file| file.poll_write(b"hello, world!")) +/// .map(|res| { +/// println!("{:?}", res); +/// }).map_err(|err| eprintln!("IO error: {:?}", err)); /// -/// tokio::run(task); -/// } +/// tokio::run(task); /// ``` /// /// Read the contents of a file into a buffer /// /// ```no_run -/// extern crate tokio; -/// /// use tokio::prelude::{AsyncRead, Future}; /// -/// fn main() { -/// let task = tokio::fs::File::open("foo.txt") -/// .and_then(|mut file| { -/// let mut contents = vec![]; -/// file.read_buf(&mut contents) -/// .map(|res| { -/// println!("{:?}", res); -/// }) -/// }).map_err(|err| eprintln!("IO error: {:?}", err)); -/// tokio::run(task); -/// } +/// let task = tokio::fs::File::open("foo.txt") +/// .and_then(|mut file| { +/// let mut contents = vec![]; +/// file.read_buf(&mut contents) +/// .map(|res| { +/// println!("{:?}", res); +/// }) +/// }).map_err(|err| eprintln!("IO error: {:?}", err)); +/// +/// tokio::run(task); /// ``` #[derive(Debug)] pub struct File { @@ -98,18 +89,17 @@ impl File { /// # Examples /// /// ```no_run - /// # extern crate tokio; /// use tokio::prelude::Future; - /// fn main() { - /// let task = tokio::fs::File::open("foo.txt").and_then(|file| { - /// // do something with the file ... - /// file.metadata().map(|md| println!("{:?}", md)) - /// }).map_err(|e| { - /// // handle errors - /// eprintln!("IO error: {:?}", e); - /// }); - /// tokio::run(task); - /// } + /// + /// let task = tokio::fs::File::open("foo.txt").and_then(|file| { + /// // do something with the file ... + /// file.metadata().map(|md| println!("{:?}", md)) + /// }).map_err(|e| { + /// // handle errors + /// eprintln!("IO error: {:?}", e); + /// }); + /// + /// tokio::run(task); /// ``` pub fn open

(path: P) -> OpenFuture

where @@ -137,19 +127,18 @@ impl File { /// # Examples /// /// ```no_run - /// # extern crate tokio; /// use tokio::prelude::Future; - /// fn main() { - /// let task = tokio::fs::File::create("foo.txt") - /// .and_then(|file| { - /// // do something with the created file ... - /// file.metadata().map(|md| println!("{:?}", md)) - /// }).map_err(|e| { - /// // handle errors - /// eprintln!("IO error: {:?}", e); - /// }); - /// tokio::run(task); - /// } + /// + /// let task = tokio::fs::File::create("foo.txt") + /// .and_then(|file| { + /// // do something with the created file ... + /// file.metadata().map(|md| println!("{:?}", md)) + /// }).map_err(|e| { + /// // handle errors + /// eprintln!("IO error: {:?}", e); + /// }); + /// + /// tokio::run(task); /// ``` pub fn create

(path: P) -> CreateFuture

where @@ -165,13 +154,10 @@ impl File { /// /// Examples /// ```no_run - /// # extern crate tokio; /// use std::fs::File; /// - /// fn main() { - /// let std_file = File::open("foo.txt").unwrap(); - /// let file = tokio::fs::File::from_std(std_file); - /// } + /// let std_file = File::open("foo.txt").unwrap(); + /// let file = tokio::fs::File::from_std(std_file); /// ``` pub fn from_std(std: StdFile) -> File { File { std: Some(std) } @@ -193,23 +179,20 @@ impl File { /// # Examples /// /// ```no_run - /// # extern crate tokio; /// use tokio::prelude::Future; /// use std::io::SeekFrom; /// - /// fn main() { - /// let task = tokio::fs::File::open("foo.txt") - /// // move cursor 6 bytes from the start of the file - /// .and_then(|mut file| file.poll_seek(SeekFrom::Start(6))) - /// .map(|res| { - /// println!("{:?}", res); - /// }).map_err(|err| eprintln!("IO error: {:?}", err)); + /// let task = tokio::fs::File::open("foo.txt") + /// // move cursor 6 bytes from the start of the file + /// .and_then(|mut file| file.poll_seek(SeekFrom::Start(6))) + /// .map(|res| { + /// println!("{:?}", res); + /// }).map_err(|err| eprintln!("IO error: {:?}", err)); /// - /// tokio::run(task); - /// } + /// tokio::run(task); /// ``` pub fn poll_seek(&mut self, pos: io::SeekFrom) -> Poll { - ::blocking_io(|| self.std().seek(pos)) + crate::blocking_io(|| self.std().seek(pos)) } /// Seek to an offset, in bytes, in a stream. @@ -222,20 +205,17 @@ impl File { /// # Examples /// /// ```no_run - /// # extern crate tokio; /// use tokio::prelude::Future; /// use std::io::SeekFrom; /// - /// fn main() { - /// let task = tokio::fs::File::create("foo.txt") - /// .and_then(|file| file.seek(SeekFrom::Start(6))) - /// .map(|file| { - /// // handle returned file .. - /// # println!("{:?}", file); - /// }).map_err(|err| eprintln!("IO error: {:?}", err)); + /// let task = tokio::fs::File::create("foo.txt") + /// .and_then(|file| file.seek(SeekFrom::Start(6))) + /// .map(|file| { + /// // handle returned file .. + /// # println!("{:?}", file); + /// }).map_err(|err| eprintln!("IO error: {:?}", err)); /// - /// tokio::run(task); - /// } + /// tokio::run(task); /// ``` pub fn seek(self, pos: io::SeekFrom) -> SeekFuture { SeekFuture::new(self, pos) @@ -249,25 +229,22 @@ impl File { /// # Examples /// /// ```no_run - /// # extern crate tokio; /// use tokio::prelude::{AsyncWrite, Future}; /// - /// fn main() { - /// let task = tokio::fs::File::create("foo.txt") - /// .and_then(|mut file| { - /// file.poll_write(b"hello, world!")?; - /// file.poll_sync_all() - /// }) - /// .map(|res| { - /// // handle returned result .. - /// # println!("{:?}", res); - /// }).map_err(|err| eprintln!("IO error: {:?}", err)); + /// let task = tokio::fs::File::create("foo.txt") + /// .and_then(|mut file| { + /// file.poll_write(b"hello, world!")?; + /// file.poll_sync_all() + /// }) + /// .map(|res| { + /// // handle returned result .. + /// # println!("{:?}", res); + /// }).map_err(|err| eprintln!("IO error: {:?}", err)); /// - /// tokio::run(task); - /// } + /// tokio::run(task); /// ``` pub fn poll_sync_all(&mut self) -> Poll<(), io::Error> { - ::blocking_io(|| self.std().sync_all()) + crate::blocking_io(|| self.std().sync_all()) } /// This function is similar to `poll_sync_all`, except that it may not @@ -282,25 +259,22 @@ impl File { /// # Examples /// /// ```no_run - /// # extern crate tokio; /// use tokio::prelude::{AsyncWrite, Future}; /// - /// fn main() { - /// let task = tokio::fs::File::create("foo.txt") - /// .and_then(|mut file| { - /// file.poll_write(b"hello, world!")?; - /// file.poll_sync_data() - /// }) - /// .map(|res| { - /// // handle returned result .. - /// # println!("{:?}", res); - /// }).map_err(|err| eprintln!("IO error: {:?}", err)); + /// let task = tokio::fs::File::create("foo.txt") + /// .and_then(|mut file| { + /// file.poll_write(b"hello, world!")?; + /// file.poll_sync_data() + /// }) + /// .map(|res| { + /// // handle returned result .. + /// # println!("{:?}", res); + /// }).map_err(|err| eprintln!("IO error: {:?}", err)); /// - /// tokio::run(task); - /// } + /// tokio::run(task); /// ``` pub fn poll_sync_data(&mut self) -> Poll<(), io::Error> { - ::blocking_io(|| self.std().sync_data()) + crate::blocking_io(|| self.std().sync_data()) } /// Truncates or extends the underlying file, updating the size of this file to become size. @@ -318,24 +292,21 @@ impl File { /// # Examples /// /// ```no_run - /// # extern crate tokio; /// use tokio::prelude::Future; /// - /// fn main() { - /// let task = tokio::fs::File::create("foo.txt") - /// .and_then(|mut file| { - /// file.poll_set_len(10) - /// }) - /// .map(|res| { - /// // handle returned result .. - /// # println!("{:?}", res); - /// }).map_err(|err| eprintln!("IO error: {:?}", err)); + /// let task = tokio::fs::File::create("foo.txt") + /// .and_then(|mut file| { + /// file.poll_set_len(10) + /// }) + /// .map(|res| { + /// // handle returned result .. + /// # println!("{:?}", res); + /// }).map_err(|err| eprintln!("IO error: {:?}", err)); /// - /// tokio::run(task); - /// } + /// tokio::run(task); /// ``` pub fn poll_set_len(&mut self, size: u64) -> Poll<(), io::Error> { - ::blocking_io(|| self.std().set_len(size)) + crate::blocking_io(|| self.std().set_len(size)) } /// Queries metadata about the underlying file. @@ -343,18 +314,15 @@ impl File { /// # Examples /// /// ```no_run - /// # extern crate tokio; /// use tokio::prelude::Future; /// - /// fn main() { - /// let task = tokio::fs::File::create("foo.txt") - /// .and_then(|file| file.metadata()) - /// .map(|metadata| { - /// println!("{:?}", metadata); - /// }).map_err(|err| eprintln!("IO error: {:?}", err)); + /// let task = tokio::fs::File::create("foo.txt") + /// .and_then(|file| file.metadata()) + /// .map(|metadata| { + /// println!("{:?}", metadata); + /// }).map_err(|err| eprintln!("IO error: {:?}", err)); /// - /// tokio::run(task); - /// } + /// tokio::run(task); /// ``` pub fn metadata(self) -> MetadataFuture { MetadataFuture::new(self) @@ -365,22 +333,19 @@ impl File { /// # Examples /// /// ```no_run - /// # extern crate tokio; /// use tokio::prelude::Future; /// - /// fn main() { - /// let task = tokio::fs::File::create("foo.txt") - /// .and_then(|mut file| file.poll_metadata()) - /// .map(|metadata| { - /// // metadata is of type Async::Ready - /// println!("{:?}", metadata); - /// }).map_err(|err| eprintln!("IO error: {:?}", err)); + /// let task = tokio::fs::File::create("foo.txt") + /// .and_then(|mut file| file.poll_metadata()) + /// .map(|metadata| { + /// // metadata is of type Async::Ready + /// println!("{:?}", metadata); + /// }).map_err(|err| eprintln!("IO error: {:?}", err)); /// - /// tokio::run(task); - /// } + /// tokio::run(task); /// ``` pub fn poll_metadata(&mut self) -> Poll { - ::blocking_io(|| self.std().metadata()) + crate::blocking_io(|| self.std().metadata()) } /// Create a new `File` instance that shares the same underlying file handle @@ -390,22 +355,19 @@ impl File { /// # Examples /// /// ```no_run - /// # extern crate tokio; /// use tokio::prelude::Future; /// - /// fn main() { - /// let task = tokio::fs::File::create("foo.txt") - /// .and_then(|mut file| file.poll_try_clone()) - /// .map(|clone| { - /// // do something with the clone - /// # println!("{:?}", clone); - /// }).map_err(|err| eprintln!("IO error: {:?}", err)); + /// let task = tokio::fs::File::create("foo.txt") + /// .and_then(|mut file| file.poll_try_clone()) + /// .map(|clone| { + /// // do something with the clone + /// # println!("{:?}", clone); + /// }).map_err(|err| eprintln!("IO error: {:?}", err)); /// - /// tokio::run(task); - /// } + /// tokio::run(task); /// ``` pub fn poll_try_clone(&mut self) -> Poll { - ::blocking_io(|| { + crate::blocking_io(|| { let std = self.std().try_clone()?; Ok(File::from_std(std)) }) @@ -416,28 +378,26 @@ impl File { /// File instances simultaneously. /// /// # Examples + /// /// ```no_run - /// # extern crate tokio; /// use tokio::prelude::Future; /// - /// fn main() { - /// let task = tokio::fs::File::create("foo.txt") - /// .and_then(|file| { - /// file.try_clone() - /// .map(|(file, clone)| { - /// // do something with the file and the clone - /// # println!("{:?} {:?}", file, clone); - /// }) - /// .map_err(|(file, err)| { - /// // you get the original file back if there's an error - /// # println!("{:?}", file); - /// err - /// }) - /// }) - /// .map_err(|err| eprintln!("IO error: {:?}", err)); + /// let task = tokio::fs::File::create("foo.txt") + /// .and_then(|file| { + /// file.try_clone() + /// .map(|(file, clone)| { + /// // do something with the file and the clone + /// # println!("{:?} {:?}", file, clone); + /// }) + /// .map_err(|(file, err)| { + /// // you get the original file back if there's an error + /// # println!("{:?}", file); + /// err + /// }) + /// }) + /// .map_err(|err| eprintln!("IO error: {:?}", err)); /// - /// tokio::run(task); - /// } + /// tokio::run(task); /// ``` pub fn try_clone(self) -> CloneFuture { CloneFuture::new(self) @@ -462,26 +422,23 @@ impl File { /// # Examples /// /// ```no_run - /// # extern crate tokio; /// use tokio::prelude::Future; /// - /// fn main() { - /// let task = tokio::fs::File::create("foo.txt") - /// .and_then(|file| file.metadata()) - /// .map(|(mut file, metadata)| { - /// let mut perms = metadata.permissions(); - /// perms.set_readonly(true); - /// match file.poll_set_permissions(perms) { - /// Err(e) => eprintln!("{}", e), - /// _ => println!("permissions set!"), - /// } - /// }).map_err(|err| eprintln!("IO error: {:?}", err)); + /// let task = tokio::fs::File::create("foo.txt") + /// .and_then(|file| file.metadata()) + /// .map(|(mut file, metadata)| { + /// let mut perms = metadata.permissions(); + /// perms.set_readonly(true); + /// match file.poll_set_permissions(perms) { + /// Err(e) => eprintln!("{}", e), + /// _ => println!("permissions set!"), + /// } + /// }).map_err(|err| eprintln!("IO error: {:?}", err)); /// - /// tokio::run(task); - /// } + /// tokio::run(task); /// ``` pub fn poll_set_permissions(&mut self, perm: Permissions) -> Poll<(), io::Error> { - ::blocking_io(|| self.std().set_permissions(perm)) + crate::blocking_io(|| self.std().set_permissions(perm)) } /// Destructures the `tokio_fs::File` into a [`std::fs::File`][std]. @@ -495,19 +452,16 @@ impl File { /// # Examples /// /// ```no_run - /// # extern crate tokio; /// use tokio::prelude::Future; /// - /// fn main() { - /// let task = tokio::fs::File::create("foo.txt") - /// .map(|file| { - /// let std_file = file.into_std(); - /// // do something with the std::fs::File - /// # println!("{:?}", std_file); - /// }).map_err(|err| eprintln!("IO error: {:?}", err)); + /// let task = tokio::fs::File::create("foo.txt") + /// .map(|file| { + /// let std_file = file.into_std(); + /// // do something with the std::fs::File + /// # println!("{:?}", std_file); + /// }).map_err(|err| eprintln!("IO error: {:?}", err)); /// - /// tokio::run(task); - /// } + /// tokio::run(task); /// ``` pub fn into_std(mut self) -> StdFile { self.std.take().expect("`File` instance already shutdown") @@ -520,7 +474,7 @@ impl File { impl Read for File { fn read(&mut self, buf: &mut [u8]) -> io::Result { - ::would_block(|| self.std().read(buf)) + crate::would_block(|| self.std().read(buf)) } } @@ -532,17 +486,17 @@ impl AsyncRead for File { impl Write for File { fn write(&mut self, buf: &[u8]) -> io::Result { - ::would_block(|| self.std().write(buf)) + crate::would_block(|| self.std().write(buf)) } fn flush(&mut self) -> io::Result<()> { - ::would_block(|| self.std().flush()) + crate::would_block(|| self.std().flush()) } } impl AsyncWrite for File { fn shutdown(&mut self) -> Poll<(), io::Error> { - ::blocking_io(|| { + crate::blocking_io(|| { self.std = None; Ok(()) }) diff --git a/tokio-fs/src/file/open.rs b/tokio-fs/src/file/open.rs index 68f7abe34..b95af1609 100644 --- a/tokio-fs/src/file/open.rs +++ b/tokio-fs/src/file/open.rs @@ -1,7 +1,5 @@ use super::File; - -use futures::{Future, Poll}; - +use futures::{try_ready, Future, Poll}; use std::fs::OpenOptions as StdOpenOptions; use std::io; use std::path::Path; @@ -30,7 +28,7 @@ where type Error = io::Error; fn poll(&mut self) -> Poll { - let std = try_ready!(::blocking_io(|| self.options.open(&self.path))); + let std = try_ready!(crate::blocking_io(|| self.options.open(&self.path))); let file = File::from_std(std); Ok(file.into()) diff --git a/tokio-fs/src/file/open_options.rs b/tokio-fs/src/file/open_options.rs index 76e0678b5..70b78211f 100644 --- a/tokio-fs/src/file/open_options.rs +++ b/tokio-fs/src/file/open_options.rs @@ -1,5 +1,4 @@ use super::OpenFuture; - use std::convert::From; use std::fs::OpenOptions as StdOpenOptions; use std::path::Path; diff --git a/tokio-fs/src/file/seek.rs b/tokio-fs/src/file/seek.rs index 373e53ce3..16f30e1be 100644 --- a/tokio-fs/src/file/seek.rs +++ b/tokio-fs/src/file/seek.rs @@ -1,7 +1,5 @@ use super::File; - -use futures::{Future, Poll}; - +use futures::{try_ready, Future, Poll}; use std::io; /// Future returned by `File::seek`. diff --git a/tokio-fs/src/hard_link.rs b/tokio-fs/src/hard_link.rs index 697427909..277eedbe7 100644 --- a/tokio-fs/src/hard_link.rs +++ b/tokio-fs/src/hard_link.rs @@ -1,9 +1,8 @@ +use futures::{Future, Poll}; use std::fs; use std::io; use std::path::Path; -use futures::{Future, Poll}; - /// Creates a new hard link on the filesystem. /// /// The `dst` path will be a link pointing to the `src` path. Note that systems @@ -46,6 +45,6 @@ where type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::hard_link(&self.src, &self.dst)) + crate::blocking_io(|| fs::hard_link(&self.src, &self.dst)) } } diff --git a/tokio-fs/src/lib.rs b/tokio-fs/src/lib.rs index ba6a95850..89b956232 100644 --- a/tokio-fs/src/lib.rs +++ b/tokio-fs/src/lib.rs @@ -1,5 +1,7 @@ -#![deny(missing_docs, missing_debug_implementations, warnings)] #![doc(html_root_url = "https://docs.rs/tokio-fs/0.1.6")] +#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! Asynchronous file and standard stream adaptation. //! @@ -28,11 +30,6 @@ //! [`AsyncRead`]: https://docs.rs/tokio-io/0.1/tokio_io/trait.AsyncRead.html //! [tokio-threadpool]: https://docs.rs/tokio-threadpool/0.1/tokio_threadpool -#[macro_use] -extern crate futures; -extern crate tokio_io; -extern crate tokio_threadpool; - mod create_dir; mod create_dir_all; pub mod file; @@ -52,28 +49,27 @@ mod stdout; mod symlink_metadata; mod write; -pub use create_dir::{create_dir, CreateDirFuture}; -pub use create_dir_all::{create_dir_all, CreateDirAllFuture}; -pub use file::File; -pub use file::OpenOptions; -pub use hard_link::{hard_link, HardLinkFuture}; -pub use metadata::{metadata, MetadataFuture}; -pub use read::{read, ReadFile}; -pub use read_dir::{read_dir, DirEntry, ReadDir, ReadDirFuture}; -pub use read_link::{read_link, ReadLinkFuture}; -pub use remove_dir::{remove_dir, RemoveDirFuture}; -pub use remove_file::{remove_file, RemoveFileFuture}; -pub use rename::{rename, RenameFuture}; -pub use set_permissions::{set_permissions, SetPermissionsFuture}; -pub use stderr::{stderr, Stderr}; -pub use stdin::{stdin, Stdin}; -pub use stdout::{stdout, Stdout}; -pub use symlink_metadata::{symlink_metadata, SymlinkMetadataFuture}; -pub use write::{write, WriteFile}; +pub use crate::create_dir::{create_dir, CreateDirFuture}; +pub use crate::create_dir_all::{create_dir_all, CreateDirAllFuture}; +pub use crate::file::File; +pub use crate::file::OpenOptions; +pub use crate::hard_link::{hard_link, HardLinkFuture}; +pub use crate::metadata::{metadata, MetadataFuture}; +pub use crate::read::{read, ReadFile}; +pub use crate::read_dir::{read_dir, DirEntry, ReadDir, ReadDirFuture}; +pub use crate::read_link::{read_link, ReadLinkFuture}; +pub use crate::remove_dir::{remove_dir, RemoveDirFuture}; +pub use crate::remove_file::{remove_file, RemoveFileFuture}; +pub use crate::rename::{rename, RenameFuture}; +pub use crate::set_permissions::{set_permissions, SetPermissionsFuture}; +pub use crate::stderr::{stderr, Stderr}; +pub use crate::stdin::{stdin, Stdin}; +pub use crate::stdout::{stdout, Stdout}; +pub use crate::symlink_metadata::{symlink_metadata, SymlinkMetadataFuture}; +pub use crate::write::{write, WriteFile}; use futures::Async::*; use futures::Poll; - use std::io; use std::io::ErrorKind::{Other, WouldBlock}; diff --git a/tokio-fs/src/metadata.rs b/tokio-fs/src/metadata.rs index 200d58e08..ece1e05ae 100644 --- a/tokio-fs/src/metadata.rs +++ b/tokio-fs/src/metadata.rs @@ -1,7 +1,5 @@ use super::blocking_io; - use futures::{Future, Poll}; - use std::fs::{self, Metadata}; use std::io; use std::path::Path; diff --git a/tokio-fs/src/os/unix.rs b/tokio-fs/src/os/unix.rs index 9bd8566b8..84b62c8f9 100644 --- a/tokio-fs/src/os/unix.rs +++ b/tokio-fs/src/os/unix.rs @@ -1,11 +1,10 @@ //! Unix-specific extensions to primitives in the `tokio_fs` module. +use futures::{Future, Poll}; use std::io; use std::os::unix::fs; use std::path::Path; -use futures::{Future, Poll}; - /// Creates a new symbolic link on the filesystem. /// /// The `dst` path will be a symbolic link pointing to the `src` path. @@ -47,6 +46,6 @@ where type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::symlink(&self.src, &self.dst)) + crate::blocking_io(|| fs::symlink(&self.src, &self.dst)) } } diff --git a/tokio-fs/src/os/windows/symlink_dir.rs b/tokio-fs/src/os/windows/symlink_dir.rs index dbf43605f..90f4a04f5 100644 --- a/tokio-fs/src/os/windows/symlink_dir.rs +++ b/tokio-fs/src/os/windows/symlink_dir.rs @@ -1,9 +1,8 @@ +use futures::{Future, Poll}; use std::io; use std::os::windows::fs; use std::path::Path; -use futures::{Future, Poll}; - /// Creates a new directory symlink on the filesystem. /// /// The `dst` path will be a directory symbolic link pointing to the `src` @@ -46,6 +45,6 @@ where type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::symlink_dir(&self.src, &self.dst)) + crate::blocking_io(|| fs::symlink_dir(&self.src, &self.dst)) } } diff --git a/tokio-fs/src/os/windows/symlink_file.rs b/tokio-fs/src/os/windows/symlink_file.rs index e27a10064..eb7c9d04e 100644 --- a/tokio-fs/src/os/windows/symlink_file.rs +++ b/tokio-fs/src/os/windows/symlink_file.rs @@ -1,9 +1,8 @@ +use futures::{Future, Poll}; use std::io; use std::os::windows::fs; use std::path::Path; -use futures::{Future, Poll}; - /// Creates a new file symbolic link on the filesystem. /// /// The `dst` path will be a file symbolic link pointing to the `src` @@ -46,6 +45,6 @@ where type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::symlink_file(&self.src, &self.dst)) + crate::blocking_io(|| fs::symlink_file(&self.src, &self.dst)) } } diff --git a/tokio-fs/src/read.rs b/tokio-fs/src/read.rs index 50d1dd7f5..fbcce0354 100644 --- a/tokio-fs/src/read.rs +++ b/tokio-fs/src/read.rs @@ -1,7 +1,7 @@ -use futures::{Async, Future, Poll}; +use crate::{file, File}; +use futures::{try_ready, Async, Future, Poll}; use std::{io, mem, path::Path}; use tokio_io; -use {file, File}; /// Creates a future which will open a file for reading and read the entire /// contents into a buffer and return said buffer. @@ -11,18 +11,17 @@ use {file, File}; /// # Examples /// /// ```no_run -/// # extern crate tokio; /// use tokio::prelude::Future; -/// fn main() { -/// let task = tokio::fs::read("foo.txt").map(|data| { -/// // do something with the contents of the file ... -/// println!("foo.txt contains {} bytes", data.len()); -/// }).map_err(|e| { -/// // handle errors -/// eprintln!("IO error: {:?}", e); -/// }); -/// tokio::run(task); -/// } +/// +/// let task = tokio::fs::read("foo.txt").map(|data| { +/// // do something with the contents of the file ... +/// println!("foo.txt contains {} bytes", data.len()); +/// }).map_err(|e| { +/// // handle errors +/// eprintln!("IO error: {:?}", e); +/// }); +/// +/// tokio::run(task); /// ``` pub fn read

(path: P) -> ReadFile

where diff --git a/tokio-fs/src/read_dir.rs b/tokio-fs/src/read_dir.rs index 05629d790..855e23328 100644 --- a/tokio-fs/src/read_dir.rs +++ b/tokio-fs/src/read_dir.rs @@ -1,3 +1,4 @@ +use futures::{Future, Poll, Stream}; use std::ffi::OsString; use std::fs::{self, DirEntry as StdDirEntry, FileType, Metadata, ReadDir as StdReadDir}; use std::io; @@ -5,8 +6,6 @@ use std::io; use std::os::unix::fs::DirEntryExt; use std::path::{Path, PathBuf}; -use futures::{Future, Poll, Stream}; - /// Returns a stream over the entries within a directory. /// /// This is an async version of [`std::fs::read_dir`][std] @@ -45,7 +44,7 @@ where type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| Ok(ReadDir(fs::read_dir(&self.path)?))) + crate::blocking_io(|| Ok(ReadDir(fs::read_dir(&self.path)?))) } } @@ -73,7 +72,7 @@ impl Stream for ReadDir { type Error = io::Error; fn poll(&mut self) -> Poll, Self::Error> { - ::blocking_io(|| match self.0.next() { + crate::blocking_io(|| match self.0.next() { Some(Err(err)) => Err(err), Some(Ok(item)) => Ok(Some(DirEntry(item))), None => Ok(None), @@ -112,18 +111,14 @@ impl DirEntry { /// # Examples /// /// ``` - /// # extern crate futures; - /// # extern crate tokio; - /// # extern crate tokio_fs; /// use futures::{Future, Stream}; /// - /// fn main() { - /// let fut = tokio_fs::read_dir(".").flatten_stream().for_each(|dir| { - /// println!("{:?}", dir.path()); - /// Ok(()) - /// }).map_err(|err| { eprintln!("Error: {:?}", err); () }); - /// tokio::run(fut); - /// } + /// let fut = tokio_fs::read_dir(".").flatten_stream().for_each(|dir| { + /// println!("{:?}", dir.path()); + /// Ok(()) + /// }).map_err(|err| { eprintln!("Error: {:?}", err); () }); + /// + /// tokio::run(fut); /// ``` /// /// This prints output like: @@ -145,19 +140,15 @@ impl DirEntry { /// # Examples /// /// ``` - /// # extern crate futures; - /// # extern crate tokio; - /// # extern crate tokio_fs; /// use futures::{Future, Stream}; /// - /// fn main() { - /// let fut = tokio_fs::read_dir(".").flatten_stream().for_each(|dir| { - /// // Here, `dir` is a `DirEntry`. - /// println!("{:?}", dir.file_name()); - /// Ok(()) - /// }).map_err(|err| { eprintln!("Error: {:?}", err); () }); - /// tokio::run(fut); - /// } + /// let fut = tokio_fs::read_dir(".").flatten_stream().for_each(|dir| { + /// // Here, `dir` is a `DirEntry`. + /// println!("{:?}", dir.file_name()); + /// Ok(()) + /// }).map_err(|err| { eprintln!("Error: {:?}", err); () }); + /// + /// tokio::run(fut); /// ``` pub fn file_name(&self) -> OsString { self.0.file_name() @@ -177,25 +168,21 @@ impl DirEntry { /// # Examples /// /// ``` - /// # extern crate futures; - /// # extern crate tokio; - /// # extern crate tokio_fs; /// use futures::{Future, Stream}; /// use futures::future::poll_fn; /// - /// fn main() { - /// let fut = tokio_fs::read_dir(".").flatten_stream().for_each(|dir| { - /// // Here, `dir` is a `DirEntry`. - /// let path = dir.path(); - /// poll_fn(move || dir.poll_metadata()).map(move |metadata| { - /// println!("{:?}: {:?}", path, metadata.permissions()); - /// }) - /// }).map_err(|err| { eprintln!("Error: {:?}", err); () }); - /// tokio::run(fut); - /// } + /// let fut = tokio_fs::read_dir(".").flatten_stream().for_each(|dir| { + /// // Here, `dir` is a `DirEntry`. + /// let path = dir.path(); + /// poll_fn(move || dir.poll_metadata()).map(move |metadata| { + /// println!("{:?}: {:?}", path, metadata.permissions()); + /// }) + /// }).map_err(|err| { eprintln!("Error: {:?}", err); () }); + /// + /// tokio::run(fut); /// ``` pub fn poll_metadata(&self) -> Poll { - ::blocking_io(|| self.0.metadata()) + crate::blocking_io(|| self.0.metadata()) } /// Return the file type for the file that this entry points at. @@ -212,26 +199,22 @@ impl DirEntry { /// # Examples /// /// ``` - /// # extern crate futures; - /// # extern crate tokio; - /// # extern crate tokio_fs; /// use futures::{Future, Stream}; /// use futures::future::poll_fn; /// - /// fn main() { - /// let fut = tokio_fs::read_dir(".").flatten_stream().for_each(|dir| { - /// // Here, `dir` is a `DirEntry`. - /// let path = dir.path(); - /// poll_fn(move || dir.poll_file_type()).map(move |file_type| { - /// // Now let's show our entry's file type! - /// println!("{:?}: {:?}", path, file_type); - /// }) - /// }).map_err(|err| { eprintln!("Error: {:?}", err); () }); - /// tokio::run(fut); - /// } + /// let fut = tokio_fs::read_dir(".").flatten_stream().for_each(|dir| { + /// // Here, `dir` is a `DirEntry`. + /// let path = dir.path(); + /// poll_fn(move || dir.poll_file_type()).map(move |file_type| { + /// // Now let's show our entry's file type! + /// println!("{:?}: {:?}", path, file_type); + /// }) + /// }).map_err(|err| { eprintln!("Error: {:?}", err); () }); + /// + /// tokio::run(fut); /// ``` pub fn poll_file_type(&self) -> Poll { - ::blocking_io(|| self.0.file_type()) + crate::blocking_io(|| self.0.file_type()) } } diff --git a/tokio-fs/src/read_link.rs b/tokio-fs/src/read_link.rs index 927c3c658..a672c97d7 100644 --- a/tokio-fs/src/read_link.rs +++ b/tokio-fs/src/read_link.rs @@ -1,9 +1,8 @@ +use futures::{Future, Poll}; use std::fs; use std::io; use std::path::{Path, PathBuf}; -use futures::{Future, Poll}; - /// Reads a symbolic link, returning the file that the link points to. /// /// This is an async version of [`std::fs::read_link`][std] @@ -39,6 +38,6 @@ where type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::read_link(&self.path)) + crate::blocking_io(|| fs::read_link(&self.path)) } } diff --git a/tokio-fs/src/remove_dir.rs b/tokio-fs/src/remove_dir.rs index 171466620..74acffe39 100644 --- a/tokio-fs/src/remove_dir.rs +++ b/tokio-fs/src/remove_dir.rs @@ -1,9 +1,8 @@ +use futures::{Future, Poll}; use std::fs; use std::io; use std::path::Path; -use futures::{Future, Poll}; - /// Removes an existing, empty directory. /// /// This is an async version of [`std::fs::remove_dir`][std] @@ -39,6 +38,6 @@ where type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::remove_dir(&self.path)) + crate::blocking_io(|| fs::remove_dir(&self.path)) } } diff --git a/tokio-fs/src/remove_file.rs b/tokio-fs/src/remove_file.rs index da273f686..d2d4b86d3 100644 --- a/tokio-fs/src/remove_file.rs +++ b/tokio-fs/src/remove_file.rs @@ -1,9 +1,8 @@ +use futures::{Future, Poll}; use std::fs; use std::io; use std::path::Path; -use futures::{Future, Poll}; - /// Removes a file from the filesystem. /// /// Note that there is no @@ -43,6 +42,6 @@ where type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::remove_file(&self.path)) + crate::blocking_io(|| fs::remove_file(&self.path)) } } diff --git a/tokio-fs/src/rename.rs b/tokio-fs/src/rename.rs index aaa8a4946..1c2977ef5 100644 --- a/tokio-fs/src/rename.rs +++ b/tokio-fs/src/rename.rs @@ -1,9 +1,8 @@ +use futures::{Future, Poll}; use std::fs; use std::io; use std::path::Path; -use futures::{Future, Poll}; - /// Rename a file or directory to a new name, replacing the original file if /// `to` already exists. /// @@ -46,6 +45,6 @@ where type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::rename(&self.from, &self.to)) + crate::blocking_io(|| fs::rename(&self.from, &self.to)) } } diff --git a/tokio-fs/src/set_permissions.rs b/tokio-fs/src/set_permissions.rs index 75f9d0fdd..dab062dc7 100644 --- a/tokio-fs/src/set_permissions.rs +++ b/tokio-fs/src/set_permissions.rs @@ -1,9 +1,8 @@ +use futures::{Future, Poll}; use std::fs; use std::io; use std::path::Path; -use futures::{Future, Poll}; - /// Changes the permissions found on a file or a directory. /// /// This is an async version of [`std::fs::set_permissions`][std] @@ -43,6 +42,6 @@ where type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::set_permissions(&self.path, self.perm.clone())) + crate::blocking_io(|| fs::set_permissions(&self.path, self.perm.clone())) } } diff --git a/tokio-fs/src/stderr.rs b/tokio-fs/src/stderr.rs index 24c1dcb1c..97ee2343c 100644 --- a/tokio-fs/src/stderr.rs +++ b/tokio-fs/src/stderr.rs @@ -1,8 +1,6 @@ -use tokio_io::AsyncWrite; - use futures::Poll; - use std::io::{self, Stderr as StdStderr, Write}; +use tokio_io::AsyncWrite; /// A handle to the standard error stream of a process. /// @@ -29,11 +27,11 @@ pub fn stderr() -> Stderr { impl Write for Stderr { fn write(&mut self, buf: &[u8]) -> io::Result { - ::would_block(|| self.std.write(buf)) + crate::would_block(|| self.std.write(buf)) } fn flush(&mut self) -> io::Result<()> { - ::would_block(|| self.std.flush()) + crate::would_block(|| self.std.flush()) } } diff --git a/tokio-fs/src/stdin.rs b/tokio-fs/src/stdin.rs index ac04c43fe..f4339047d 100644 --- a/tokio-fs/src/stdin.rs +++ b/tokio-fs/src/stdin.rs @@ -1,6 +1,5 @@ -use tokio_io::AsyncRead; - use std::io::{self, Read, Stdin as StdStdin}; +use tokio_io::AsyncRead; /// A handle to the standard input stream of a process. /// @@ -33,7 +32,7 @@ pub fn stdin() -> Stdin { impl Read for Stdin { fn read(&mut self, buf: &mut [u8]) -> io::Result { - ::would_block(|| self.std.read(buf)) + crate::would_block(|| self.std.read(buf)) } } diff --git a/tokio-fs/src/stdout.rs b/tokio-fs/src/stdout.rs index 0c2bdc54f..6141d7dd4 100644 --- a/tokio-fs/src/stdout.rs +++ b/tokio-fs/src/stdout.rs @@ -1,8 +1,6 @@ -use tokio_io::AsyncWrite; - use futures::Poll; - use std::io::{self, Stdout as StdStdout, Write}; +use tokio_io::AsyncWrite; /// A handle to the standard output stream of a process. /// @@ -29,11 +27,11 @@ pub fn stdout() -> Stdout { impl Write for Stdout { fn write(&mut self, buf: &[u8]) -> io::Result { - ::would_block(|| self.std.write(buf)) + crate::would_block(|| self.std.write(buf)) } fn flush(&mut self) -> io::Result<()> { - ::would_block(|| self.std.flush()) + crate::would_block(|| self.std.flush()) } } diff --git a/tokio-fs/src/symlink_metadata.rs b/tokio-fs/src/symlink_metadata.rs index db02769e2..f3b256aa3 100644 --- a/tokio-fs/src/symlink_metadata.rs +++ b/tokio-fs/src/symlink_metadata.rs @@ -1,7 +1,5 @@ use super::blocking_io; - use futures::{Future, Poll}; - use std::fs::{self, Metadata}; use std::io; use std::path::Path; diff --git a/tokio-fs/src/write.rs b/tokio-fs/src/write.rs index 3f49cc01c..b6f7511d0 100644 --- a/tokio-fs/src/write.rs +++ b/tokio-fs/src/write.rs @@ -1,7 +1,7 @@ -use futures::{Async, Future, Poll}; +use crate::{file, File}; +use futures::{try_ready, Async, Future, Poll}; use std::{fmt, io, mem, path::Path}; use tokio_io; -use {file, File}; /// Creates a future that will open a file for writing and write the entire /// contents of `contents` to it. @@ -11,20 +11,19 @@ use {file, File}; /// # Examples /// /// ```no_run -/// # extern crate tokio; /// use tokio::prelude::Future; -/// fn main() { -/// let buffer = b"Hello world!"; -/// let task = tokio::fs::write("foo.txt", buffer).map(|data| { -/// // `data` has now been written to foo.txt. The buffer is being -/// // returned so it can be used for other things. -/// println!("foo.txt now had {} bytes written to it", data.len()); -/// }).map_err(|e| { -/// // handle errors -/// eprintln!("IO error: {:?}", e); -/// }); -/// tokio::run(task); -/// } +/// +/// let buffer = b"Hello world!"; +/// let task = tokio::fs::write("foo.txt", buffer).map(|data| { +/// // `data` has now been written to foo.txt. The buffer is being +/// // returned so it can be used for other things. +/// println!("foo.txt now had {} bytes written to it", data.len()); +/// }).map_err(|e| { +/// // handle errors +/// eprintln!("IO error: {:?}", e); +/// }); +/// +/// tokio::run(task); /// ``` pub fn write>(path: P, contents: C) -> WriteFile where diff --git a/tokio-fs/tests/dir.rs b/tokio-fs/tests/dir.rs index 3a1ed351a..a22c048ea 100644 --- a/tokio-fs/tests/dir.rs +++ b/tokio-fs/tests/dir.rs @@ -1,6 +1,4 @@ -extern crate futures; -extern crate tempdir; -extern crate tokio_fs; +#![deny(warnings, rust_2018_idioms)] use futures::{Future, Stream}; use std::fs; diff --git a/tokio-fs/tests/file.rs b/tokio-fs/tests/file.rs index b8221a3eb..421c0b36b 100644 --- a/tokio-fs/tests/file.rs +++ b/tokio-fs/tests/file.rs @@ -1,19 +1,13 @@ -extern crate futures; -extern crate rand; -extern crate tempfile; -extern crate tokio_fs; -extern crate tokio_io; - -use tokio_fs::*; -use tokio_io::io; +#![deny(warnings, rust_2018_idioms)] use futures::future::poll_fn; use futures::Future; use rand::{distributions, thread_rng, Rng}; -use tempfile::Builder as TmpBuilder; - use std::fs; use std::io::SeekFrom; +use tempfile::Builder as TmpBuilder; +use tokio_fs::*; +use tokio_io::io; mod pool; diff --git a/tokio-fs/tests/link.rs b/tokio-fs/tests/link.rs index 11e6f45fc..33364d985 100644 --- a/tokio-fs/tests/link.rs +++ b/tokio-fs/tests/link.rs @@ -1,8 +1,5 @@ -extern crate futures; -extern crate tempdir; -extern crate tokio_fs; +#![deny(warnings, rust_2018_idioms)] -use futures::Future; use std::fs; use std::io::prelude::*; use std::io::BufReader; @@ -38,6 +35,8 @@ fn test_hard_link() { #[cfg(unix)] #[test] fn test_symlink() { + use futures::Future; + let dir = TempDir::new("base").unwrap(); let src = dir.path().join("src.txt"); let dst = dir.path().join("dst.txt"); diff --git a/tokio-fs/tests/pool/mod.rs b/tokio-fs/tests/pool/mod.rs index 9bf7d80ca..eeadd2123 100644 --- a/tokio-fs/tests/pool/mod.rs +++ b/tokio-fs/tests/pool/mod.rs @@ -1,5 +1,5 @@ -extern crate futures; -extern crate tokio_threadpool; +use futures; +use tokio_threadpool; use self::tokio_threadpool::Builder; use futures::sync::oneshot; diff --git a/tokio-futures/Cargo.toml b/tokio-futures/Cargo.toml index bec1463e1..46ebda170 100644 --- a/tokio-futures/Cargo.toml +++ b/tokio-futures/Cargo.toml @@ -3,7 +3,8 @@ name = "tokio-futures" # When releasing to crates.io: # - Update html_root_url. -version = "0.1.0" +version = "0.2.0" +edition = "2018" authors = ["Carl Lerche "] license = "MIT" repository = "https://github.com/tokio-rs/tokio" @@ -13,6 +14,7 @@ description = """ Experimental std::future::Future and async/await support for Tokio """ categories = ["asynchronous"] +publish = false [features] # This feature comes with no promise of stability. Things will @@ -21,9 +23,9 @@ async-await-preview = ["futures/nightly"] [dependencies] futures = "0.1.23" -tokio-io = "0.1.7" +tokio-io = { version = "0.2.0", path = "../tokio-io" } [dev-dependencies] bytes = "0.4.9" hyper = "0.12.8" -tokio = { version = "0.1.8", path = "../tokio" } +tokio = { version = "0.2.0", path = "../tokio" } diff --git a/tokio-futures/README.md b/tokio-futures/README.md index 358ed866e..6d9455448 100644 --- a/tokio-futures/README.md +++ b/tokio-futures/README.md @@ -18,19 +18,14 @@ Add this to your `Cargo.toml`: edition = "2018" # In the `[dependencies]` section -tokio = {version = "0.1.15", features = ["async-await-preview"]} +tokio = {version = "0.2.0", features = ["async-await-preview"]} ``` Then, get started. In your application, add: ```rust // The nightly features that are commonly needed with async / await -#![feature(await_macro, async_await)] - -// This pulls in the `tokio-futures` crate. While Rust 2018 doesn't require -// `extern crate`, we need to pull in the macros. -#[macro_use] -extern crate tokio; +#![feature(async_await)] fn main() { // And we are async... diff --git a/tokio-futures/src/await.rs b/tokio-futures/src/async_wait.rs similarity index 84% rename from tokio-futures/src/await.rs rename to tokio-futures/src/async_wait.rs index 1e8f6e7eb..e626f99e6 100644 --- a/tokio-futures/src/await.rs +++ b/tokio-futures/src/async_wait.rs @@ -1,16 +1,15 @@ /// Wait for a future to complete. #[macro_export] -macro_rules! await { +macro_rules! async_wait { ($e:expr) => {{ #[allow(unused_imports)] use $crate::compat::backward::IntoAwaitable as IntoAwaitableBackward; #[allow(unused_imports)] use $crate::compat::forward::IntoAwaitable as IntoAwaitableForward; - use $crate::std_await; #[allow(unused_mut)] let mut e = $e; let e = e.into_awaitable(); - std_await!(e) + e.await }}; } diff --git a/tokio-futures/src/compat/forward.rs b/tokio-futures/src/compat/forward.rs index f343bec49..f6cb68750 100644 --- a/tokio-futures/src/compat/forward.rs +++ b/tokio-futures/src/compat/forward.rs @@ -55,7 +55,7 @@ where { type Output = Result; - fn poll(mut self: Pin<&mut Self>, _context: &mut Context) -> StdPoll { + fn poll(mut self: Pin<&mut Self>, _context: &mut Context<'_>) -> StdPoll { use futures::Async::{NotReady, Ready}; // TODO: wire in cx diff --git a/tokio-futures/src/compat/mod.rs b/tokio-futures/src/compat/mod.rs index 88025b4e4..86940dafb 100644 --- a/tokio-futures/src/compat/mod.rs +++ b/tokio-futures/src/compat/mod.rs @@ -30,7 +30,7 @@ where impl std::future::Future for Map { type Output = Result; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { match self.future().poll(cx) { Poll::Ready(v) => Poll::Ready(Ok(v)), Poll::Pending => Poll::Pending, diff --git a/tokio-futures/src/io/flush.rs b/tokio-futures/src/io/flush.rs index 4920581d7..9984bf28e 100644 --- a/tokio-futures/src/io/flush.rs +++ b/tokio-futures/src/io/flush.rs @@ -1,13 +1,12 @@ -use tokio_io::AsyncWrite; - use std::future::Future; use std::io; use std::pin::Pin; use std::task::{Context, Poll}; +use tokio_io::AsyncWrite; /// A future used to fully flush an I/O object. #[derive(Debug)] -pub struct Flush<'a, T: ?Sized + 'a> { +pub struct Flush<'a, T: ?Sized> { writer: &'a mut T, } @@ -23,7 +22,7 @@ impl<'a, T: AsyncWrite + ?Sized> Flush<'a, T> { impl<'a, T: AsyncWrite + ?Sized> Future for Flush<'a, T> { type Output = io::Result<()>; - fn poll(mut self: Pin<&mut Self>, _context: &mut Context) -> Poll { + fn poll(mut self: Pin<&mut Self>, _context: &mut Context<'_>) -> Poll { use crate::compat::forward::convert_poll; convert_poll(self.writer.poll_flush()) } diff --git a/tokio-futures/src/io/mod.rs b/tokio-futures/src/io/mod.rs index 623a62dfc..b0a26e310 100644 --- a/tokio-futures/src/io/mod.rs +++ b/tokio-futures/src/io/mod.rs @@ -25,7 +25,7 @@ pub trait AsyncReadExt: AsyncRead { /// # Examples /// /// ```edition2018 - /// #![feature(async_await, await_macro)] + /// #![feature(async_await)] /// tokio::run_async(async { /// // The extension trait can also be imported with /// // `use tokio::prelude::*`. @@ -35,7 +35,7 @@ pub trait AsyncReadExt: AsyncRead { /// let mut reader = Cursor::new([1, 2, 3, 4]); /// let mut output = [0u8; 5]; /// - /// let bytes = await!(reader.read_async(&mut output[..])).unwrap(); + /// let bytes = reader.read_async(&mut output[..]).await.unwrap(); /// /// // This is only guaranteed to be 4 because `&[u8]` is a synchronous /// // reader. In a real system you could get anywhere from 1 to @@ -59,7 +59,7 @@ pub trait AsyncReadExt: AsyncRead { /// # Examples /// /// ```edition2018 - /// #![feature(async_await, await_macro)] + /// #![feature(async_await)] /// tokio::run_async(async { /// // The extension trait can also be imported with /// // `use tokio::prelude::*`. @@ -69,7 +69,7 @@ pub trait AsyncReadExt: AsyncRead { /// let mut reader = Cursor::new([1, 2, 3, 4]); /// let mut output = [0u8; 4]; /// - /// await!(reader.read_exact_async(&mut output)).unwrap(); + /// reader.read_exact_async(&mut output).await.unwrap(); /// /// assert_eq!(output, [1, 2, 3, 4]); /// }); @@ -78,7 +78,7 @@ pub trait AsyncReadExt: AsyncRead { /// ## EOF is hit before `buf` is filled /// /// ```edition2018 - /// #![feature(async_await, await_macro)] + /// #![feature(async_await)] /// tokio::run_async(async { /// // The extension trait can also be imported with /// // `use tokio::prelude::*`. @@ -88,7 +88,7 @@ pub trait AsyncReadExt: AsyncRead { /// let mut reader = Cursor::new([1, 2, 3, 4]); /// let mut output = [0u8; 5]; /// - /// let result = await!(reader.read_exact_async(&mut output)); + /// let result = reader.read_exact_async(&mut output).await; /// /// assert_eq!(result.unwrap_err().kind(), io::ErrorKind::UnexpectedEof); /// }); @@ -110,7 +110,7 @@ pub trait AsyncWriteExt: AsyncWrite { /// # Examples /// /// ```edition2018 - /// #![feature(async_await, await_macro)] + /// #![feature(async_await)] /// tokio::run_async(async { /// // The extension trait can also be imported with /// // `use tokio::prelude::*`. @@ -120,7 +120,7 @@ pub trait AsyncWriteExt: AsyncWrite { /// let mut buf = [0u8; 5]; /// let mut writer = Cursor::new(&mut buf[..]); /// - /// let n = await!(writer.write_async(&[1, 2, 3, 4])).unwrap(); + /// let n = writer.write_async(&[1, 2, 3, 4]).await.unwrap(); /// /// assert_eq!(writer.into_inner()[..n], [1, 2, 3, 4, 0][..n]); /// }); @@ -139,7 +139,7 @@ pub trait AsyncWriteExt: AsyncWrite { /// # Examples /// /// ```edition2018 - /// #![feature(async_await, await_macro)] + /// #![feature(async_await)] /// tokio::run_async(async { /// // The extension trait can also be imported with /// // `use tokio::prelude::*`. @@ -149,7 +149,7 @@ pub trait AsyncWriteExt: AsyncWrite { /// let mut buf = [0u8; 5]; /// let mut writer = Cursor::new(&mut buf[..]); /// - /// await!(writer.write_all_async(&[1, 2, 3, 4])).unwrap(); + /// writer.write_all_async(&[1, 2, 3, 4]).await.unwrap(); /// /// assert_eq!(writer.into_inner(), [1, 2, 3, 4, 0]); /// }); @@ -163,7 +163,7 @@ pub trait AsyncWriteExt: AsyncWrite { /// # Examples /// /// ```edition2018 - /// #![feature(async_await, await_macro)] + /// #![feature(async_await)] /// tokio::run_async(async { /// // The extension trait can also be imported with /// // `use tokio::prelude::*`. @@ -175,15 +175,15 @@ pub trait AsyncWriteExt: AsyncWrite { /// { /// let mut writer = Cursor::new(&mut output[..]); /// let mut buffered = BufWriter::new(writer); - /// await!(buffered.write_all_async(&[1, 2])).unwrap(); - /// await!(buffered.write_all_async(&[3, 4])).unwrap(); - /// await!(buffered.flush_async()).unwrap(); + /// buffered.write_all_async(&[1, 2]).await.unwrap(); + /// buffered.write_all_async(&[3, 4]).await.unwrap(); + /// buffered.flush_async().await.unwrap(); /// } /// /// assert_eq!(output, [1, 2, 3, 4, 0]); /// }); /// ``` - fn flush_async<'a>(&mut self) -> Flush { + fn flush_async<'a>(&mut self) -> Flush<'_, Self> { Flush::new(self) } } diff --git a/tokio-futures/src/io/read.rs b/tokio-futures/src/io/read.rs index 08a441bc8..7a467b8df 100644 --- a/tokio-futures/src/io/read.rs +++ b/tokio-futures/src/io/read.rs @@ -1,14 +1,12 @@ -use tokio_io::AsyncRead; - use std::future::Future; -use std::task::{self, Poll}; - use std::io; use std::pin::Pin; +use std::task::{self, Poll}; +use tokio_io::AsyncRead; /// A future which can be used to read bytes. #[derive(Debug)] -pub struct Read<'a, T: ?Sized + 'a> { +pub struct Read<'a, T: ?Sized> { reader: &'a mut T, buf: &'a mut [u8], } @@ -25,7 +23,7 @@ impl<'a, T: AsyncRead + ?Sized> Read<'a, T> { impl<'a, T: AsyncRead + ?Sized> Future for Read<'a, T> { type Output = io::Result; - fn poll(mut self: Pin<&mut Self>, _context: &mut task::Context) -> Poll { + fn poll(mut self: Pin<&mut Self>, _context: &mut task::Context<'_>) -> Poll { use crate::compat::forward::convert_poll; let this = &mut *self; diff --git a/tokio-futures/src/io/read_exact.rs b/tokio-futures/src/io/read_exact.rs index 931fc4cae..82344beaf 100644 --- a/tokio-futures/src/io/read_exact.rs +++ b/tokio-futures/src/io/read_exact.rs @@ -1,15 +1,13 @@ -use tokio_io::AsyncRead; - use std::future::Future; -use std::task::{self, Poll}; - use std::io; use std::mem; use std::pin::Pin; +use std::task::{self, Poll}; +use tokio_io::AsyncRead; /// A future which can be used to read exactly enough bytes to fill a buffer. #[derive(Debug)] -pub struct ReadExact<'a, T: ?Sized + 'a> { +pub struct ReadExact<'a, T: ?Sized> { reader: &'a mut T, buf: &'a mut [u8], } @@ -30,7 +28,7 @@ fn eof() -> io::Error { impl<'a, T: AsyncRead + ?Sized> Future for ReadExact<'a, T> { type Output = io::Result<()>; - fn poll(mut self: Pin<&mut Self>, _context: &mut task::Context) -> Poll { + fn poll(mut self: Pin<&mut Self>, _context: &mut task::Context<'_>) -> Poll { use crate::compat::forward::convert_poll; let this = &mut *self; diff --git a/tokio-futures/src/io/write.rs b/tokio-futures/src/io/write.rs index ca62c943d..26f0a4a1b 100644 --- a/tokio-futures/src/io/write.rs +++ b/tokio-futures/src/io/write.rs @@ -1,14 +1,12 @@ -use tokio_io::AsyncWrite; - use std::future::Future; -use std::task::{self, Poll}; - use std::io; use std::pin::Pin; +use std::task::{self, Poll}; +use tokio_io::AsyncWrite; /// A future used to write data. #[derive(Debug)] -pub struct Write<'a, T: 'a + ?Sized> { +pub struct Write<'a, T: ?Sized> { writer: &'a mut T, buf: &'a [u8], } @@ -25,7 +23,7 @@ impl<'a, T: AsyncWrite + ?Sized> Write<'a, T> { impl<'a, T: AsyncWrite + ?Sized> Future for Write<'a, T> { type Output = io::Result; - fn poll(mut self: Pin<&mut Self>, _context: &mut task::Context) -> Poll> { + fn poll(mut self: Pin<&mut Self>, _context: &mut task::Context<'_>) -> Poll> { use crate::compat::forward::convert_poll; let this = &mut *self; diff --git a/tokio-futures/src/io/write_all.rs b/tokio-futures/src/io/write_all.rs index 172337e05..d207a3c90 100644 --- a/tokio-futures/src/io/write_all.rs +++ b/tokio-futures/src/io/write_all.rs @@ -1,15 +1,13 @@ -use tokio_io::AsyncWrite; - use std::future::Future; -use std::task::{self, Poll}; - use std::io; use std::mem; use std::pin::Pin; +use std::task::{self, Poll}; +use tokio_io::AsyncWrite; /// A future used to write the entire contents of a buffer. #[derive(Debug)] -pub struct WriteAll<'a, T: ?Sized + 'a> { +pub struct WriteAll<'a, T: ?Sized> { writer: &'a mut T, buf: &'a [u8], } @@ -30,7 +28,7 @@ fn zero_write() -> io::Error { impl<'a, T: AsyncWrite + ?Sized> Future for WriteAll<'a, T> { type Output = io::Result<()>; - fn poll(mut self: Pin<&mut Self>, _context: &mut task::Context) -> Poll> { + fn poll(mut self: Pin<&mut Self>, _context: &mut task::Context<'_>) -> Poll> { use crate::compat::forward::convert_poll; let this = &mut *self; diff --git a/tokio-futures/src/lib.rs b/tokio-futures/src/lib.rs index 411dc424e..37ffd1b90 100644 --- a/tokio-futures/src/lib.rs +++ b/tokio-futures/src/lib.rs @@ -1,14 +1,12 @@ #![cfg(feature = "async-await-preview")] -#![feature(await_macro)] +#![feature(async_await, await_macro)] #![doc(html_root_url = "https://docs.rs/tokio-futures/0.1.0")] -#![deny(missing_docs, missing_debug_implementations)] +#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)] #![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! A preview of Tokio w/ `async` / `await` support. -extern crate futures; -extern crate tokio_io; - /// Extracts the successful type of a `Poll>`. /// /// This macro bakes in propagation of `Pending` and `Err` signals by returning early. @@ -23,13 +21,8 @@ macro_rules! try_ready { } #[macro_use] -mod await; +mod async_wait; pub mod compat; pub mod io; pub mod sink; pub mod stream; - -// Rename the `await` macro in `std`. This is used by the redefined -// `await` macro in this crate. -#[doc(hidden)] -pub use std::await as std_await; diff --git a/tokio-futures/src/sink/mod.rs b/tokio-futures/src/sink/mod.rs index 4edc0517b..90382951e 100644 --- a/tokio-futures/src/sink/mod.rs +++ b/tokio-futures/src/sink/mod.rs @@ -13,7 +13,7 @@ pub trait SinkExt: Sink { /// Note that, **because of the flushing requirement, it is usually better /// to batch together items to send via `send_all`, rather than flushing /// between each item.** - fn send_async(&mut self, item: Self::SinkItem) -> Send + fn send_async(&mut self, item: Self::SinkItem) -> Send<'_, Self> where Self: Sized + Unpin, { diff --git a/tokio-futures/src/sink/send.rs b/tokio-futures/src/sink/send.rs index dd8b58adf..b2e28c249 100644 --- a/tokio-futures/src/sink/send.rs +++ b/tokio-futures/src/sink/send.rs @@ -1,14 +1,12 @@ use futures::Sink; - use std::future::Future; -use std::task::{self, Poll}; - use std::pin::Pin; +use std::task::{self, Poll}; /// Future for the `SinkExt::send_async` combinator, which sends a value to a /// sink and then waits until the sink has fully flushed. #[derive(Debug)] -pub struct Send<'a, T: Sink + 'a + ?Sized> { +pub struct Send<'a, T: Sink + ?Sized> { sink: &'a mut T, item: Option, } @@ -27,7 +25,7 @@ impl<'a, T: Sink + Unpin + ?Sized> Send<'a, T> { impl Future for Send<'_, T> { type Output = Result<(), T::SinkError>; - fn poll(mut self: Pin<&mut Self>, _context: &mut task::Context) -> Poll { + fn poll(mut self: Pin<&mut Self>, _context: &mut task::Context<'_>) -> Poll { use crate::compat::forward::convert_poll; use futures::AsyncSink::{NotReady, Ready}; diff --git a/tokio-futures/src/stream/mod.rs b/tokio-futures/src/stream/mod.rs index db2fe0425..a6d987d61 100644 --- a/tokio-futures/src/stream/mod.rs +++ b/tokio-futures/src/stream/mod.rs @@ -13,7 +13,7 @@ pub trait StreamExt: Stream { /// # Examples /// /// ```edition2018 - /// #![feature(await_macro, async_await)] + /// #![feature(async_await)] /// tokio::run_async(async { /// // The extension trait can also be imported with /// // `use tokio::prelude::*`. @@ -21,13 +21,13 @@ pub trait StreamExt: Stream { /// /// let mut stream = stream::iter_ok::<_, ()>(1..3); /// - /// assert_eq!(await!(stream.next()), Some(Ok(1))); - /// assert_eq!(await!(stream.next()), Some(Ok(2))); - /// assert_eq!(await!(stream.next()), Some(Ok(3))); - /// assert_eq!(await!(stream.next()), None); + /// assert_eq!(stream.next().await, Some(Ok(1))); + /// assert_eq!(stream.next().await, Some(Ok(2))); + /// assert_eq!(stream.next().await, Some(Ok(3))); + /// assert_eq!(stream.next().await, None); /// }); /// ``` - fn next(&mut self) -> Next + fn next(&mut self) -> Next<'_, Self> where Self: Sized + Unpin, { diff --git a/tokio-futures/src/stream/next.rs b/tokio-futures/src/stream/next.rs index 7cd4eafa4..ab56fd874 100644 --- a/tokio-futures/src/stream/next.rs +++ b/tokio-futures/src/stream/next.rs @@ -1,12 +1,11 @@ use futures::Stream; - use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; /// A future of the next element of a stream. #[derive(Debug)] -pub struct Next<'a, T: 'a> { +pub struct Next<'a, T> { stream: &'a mut T, } @@ -21,7 +20,7 @@ impl<'a, T: Stream + Unpin> Next<'a, T> { impl<'a, T: Stream + Unpin> Future for Next<'a, T> { type Output = Option>; - fn poll(mut self: Pin<&mut Self>, _context: &mut Context) -> Poll { + fn poll(mut self: Pin<&mut Self>, _context: &mut Context<'_>) -> Poll { use crate::compat::forward::convert_poll_stream; convert_poll_stream(self.stream.poll()) diff --git a/tokio-io/Cargo.toml b/tokio-io/Cargo.toml index 759534f10..2ccbe4fe2 100644 --- a/tokio-io/Cargo.toml +++ b/tokio-io/Cargo.toml @@ -8,7 +8,8 @@ name = "tokio-io" # - README.md # - Update CHANGELOG.md. # - Create "v0.1.x" git tag. -version = "0.1.12" +version = "0.2.0" +edition = "2018" authors = ["Carl Lerche "] license = "MIT" repository = "https://github.com/tokio-rs/tokio" @@ -18,6 +19,7 @@ description = """ Core I/O primitives for asynchronous I/O in Rust. """ categories = ["asynchronous"] +publish = false [dependencies] bytes = "0.4.7" @@ -25,4 +27,4 @@ futures = "0.1.18" log = "0.4" [dev-dependencies] -tokio-current-thread = "0.1.1" +tokio-current-thread = { version = "0.2.0", path = "../tokio-current-thread" } diff --git a/tokio-io/README.md b/tokio-io/README.md index f261524b0..82ea3d57e 100644 --- a/tokio-io/README.md +++ b/tokio-io/README.md @@ -8,19 +8,13 @@ Core I/O abstractions for the Tokio stack. ## Usage -First, add this to your `Cargo.toml`: +Add this to your `Cargo.toml`: ```toml [dependencies] tokio-io = "0.1" ``` -Next, add this to your crate: - -```rust -extern crate tokio_io; -``` - You can find extensive documentation and examples about how to use this crate online at [https://tokio.rs](https://tokio.rs). The [API documentation](https://docs.rs/tokio-io) is also a great place to get started diff --git a/tokio-io/src/_tokio_codec/decoder.rs b/tokio-io/src/_tokio_codec/decoder.rs index edc0ecc0d..da34aeeed 100644 --- a/tokio-io/src/_tokio_codec/decoder.rs +++ b/tokio-io/src/_tokio_codec/decoder.rs @@ -1,3 +1,3 @@ // For now, we need to keep the implementation of Encoder in tokio_io. -pub use codec::Decoder; +pub use crate::codec::Decoder; diff --git a/tokio-io/src/_tokio_codec/encoder.rs b/tokio-io/src/_tokio_codec/encoder.rs index 20b9e375e..b84a3ba77 100644 --- a/tokio-io/src/_tokio_codec/encoder.rs +++ b/tokio-io/src/_tokio_codec/encoder.rs @@ -1,3 +1,3 @@ // For now, we need to keep the implementation of Encoder in tokio_io. -pub use codec::Encoder; +pub use crate::codec::Encoder; diff --git a/tokio-io/src/_tokio_codec/framed.rs b/tokio-io/src/_tokio_codec/framed.rs index d290575e7..88426c990 100644 --- a/tokio-io/src/_tokio_codec/framed.rs +++ b/tokio-io/src/_tokio_codec/framed.rs @@ -1,15 +1,13 @@ #![allow(deprecated)] -use std::fmt; -use std::io::{self, Read, Write}; - use super::framed_read::{framed_read2, framed_read2_with_buffer, FramedRead2}; use super::framed_write::{framed_write2, framed_write2_with_buffer, FramedWrite2}; -use codec::{Decoder, Encoder}; -use {AsyncRead, AsyncWrite}; - +use crate::codec::{Decoder, Encoder}; +use crate::{AsyncRead, AsyncWrite}; use bytes::BytesMut; use futures::{Poll, Sink, StartSend, Stream}; +use std::fmt; +use std::io::{self, Read, Write}; /// A unified `Stream` and `Sink` interface to an underlying I/O object, using /// the `Encoder` and `Decoder` traits to encode and decode frames. @@ -187,7 +185,7 @@ where T: fmt::Debug, U: fmt::Debug, { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Framed") .field("io", &self.inner.get_ref().get_ref().0) .field("codec", &self.inner.get_ref().get_ref().1) diff --git a/tokio-io/src/_tokio_codec/framed_read.rs b/tokio-io/src/_tokio_codec/framed_read.rs index ea7550877..a12851700 100644 --- a/tokio-io/src/_tokio_codec/framed_read.rs +++ b/tokio-io/src/_tokio_codec/framed_read.rs @@ -1,13 +1,12 @@ #![allow(deprecated)] -use std::fmt; - use super::framed::Fuse; -use codec::Decoder; -use AsyncRead; - +use crate::codec::Decoder; +use crate::AsyncRead; use bytes::BytesMut; -use futures::{Async, Poll, Sink, StartSend, Stream}; +use futures::{try_ready, Async, Poll, Sink, StartSend, Stream}; +use log::trace; +use std::fmt; /// A `Stream` of messages decoded from an `AsyncRead`. pub struct FramedRead { @@ -117,7 +116,7 @@ where T: fmt::Debug, D: fmt::Debug, { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("FramedRead") .field("inner", &self.inner.inner.0) .field("decoder", &self.inner.inner.1) diff --git a/tokio-io/src/_tokio_codec/framed_write.rs b/tokio-io/src/_tokio_codec/framed_write.rs index 7541b1730..7ea7e6262 100644 --- a/tokio-io/src/_tokio_codec/framed_write.rs +++ b/tokio-io/src/_tokio_codec/framed_write.rs @@ -1,15 +1,14 @@ #![allow(deprecated)] +use super::framed::Fuse; +use crate::codec::{Decoder, Encoder}; +use crate::{AsyncRead, AsyncWrite}; +use bytes::BytesMut; +use futures::{try_ready, Async, AsyncSink, Poll, Sink, StartSend, Stream}; +use log::trace; use std::fmt; use std::io::{self, Read}; -use super::framed::Fuse; -use codec::{Decoder, Encoder}; -use {AsyncRead, AsyncWrite}; - -use bytes::BytesMut; -use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; - /// A `Sink` of frames encoded to an `AsyncWrite`. pub struct FramedWrite { inner: FramedWrite2>, @@ -115,7 +114,7 @@ where T: fmt::Debug, U: fmt::Debug, { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("FramedWrite") .field("inner", &self.inner.get_ref().0) .field("encoder", &self.inner.get_ref().1) diff --git a/tokio-io/src/_tokio_codec/mod.rs b/tokio-io/src/_tokio_codec/mod.rs index 1c703f3a4..269fee26b 100644 --- a/tokio-io/src/_tokio_codec/mod.rs +++ b/tokio-io/src/_tokio_codec/mod.rs @@ -10,7 +10,6 @@ //! [`Stream`]: # //! [transports]: # -#![deny(missing_docs, missing_debug_implementations, warnings)] #![doc(hidden, html_root_url = "https://docs.rs/tokio-codec/0.1.0")] // _tokio_codec are the items that belong in the `tokio_codec` crate. However, because we need to diff --git a/tokio-io/src/allow_std.rs b/tokio-io/src/allow_std.rs index af39ac219..c86ccca43 100644 --- a/tokio-io/src/allow_std.rs +++ b/tokio-io/src/allow_std.rs @@ -1,6 +1,6 @@ +use crate::{AsyncRead, AsyncWrite}; use futures::{Async, Poll}; use std::{fmt, io}; -use {AsyncRead, AsyncWrite}; /// A simple wrapper type which allows types that only implement /// `std::io::Read` or `std::io::Write` to be used in contexts which expect @@ -50,7 +50,7 @@ where fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.0.write_all(buf) } - fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> { + fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { self.0.write_fmt(fmt) } } diff --git a/tokio-io/src/async_read.rs b/tokio-io/src/async_read.rs index d82aa7116..e2251ef60 100644 --- a/tokio-io/src/async_read.rs +++ b/tokio-io/src/async_read.rs @@ -1,11 +1,10 @@ -use bytes::BufMut; -use futures::{Async, Poll}; -use std::io as std_io; - #[allow(deprecated)] -use codec::{Decoder, Encoder, Framed}; -use split::{ReadHalf, WriteHalf}; -use {framed, split, AsyncWrite}; +use crate::codec::{Decoder, Encoder, Framed}; +use crate::split::{ReadHalf, WriteHalf}; +use crate::{framed, split, AsyncWrite}; +use bytes::BufMut; +use futures::{try_ready, Async, Poll}; +use std::io as std_io; /// Read bytes asynchronously. /// diff --git a/tokio-io/src/async_write.rs b/tokio-io/src/async_write.rs index 0a09480e8..fe5585018 100644 --- a/tokio-io/src/async_write.rs +++ b/tokio-io/src/async_write.rs @@ -1,9 +1,8 @@ +use crate::AsyncRead; use bytes::Buf; -use futures::{Async, Poll}; +use futures::{try_ready, Async, Poll}; use std::io as std_io; -use AsyncRead; - /// Writes bytes asynchronously. /// /// The trait inherits from `std::io::Write` and indicates that an I/O object is diff --git a/tokio-io/src/codec/bytes_codec.rs b/tokio-io/src/codec/bytes_codec.rs index ecfd15ab9..66369478e 100644 --- a/tokio-io/src/codec/bytes_codec.rs +++ b/tokio-io/src/codec/bytes_codec.rs @@ -1,7 +1,7 @@ #![allow(deprecated)] +use crate::codec::{Decoder, Encoder}; use bytes::{BufMut, Bytes, BytesMut}; -use codec::{Decoder, Encoder}; use std::io; /// A simple `Codec` implementation that just ships bytes around. diff --git a/tokio-io/src/codec/decoder.rs b/tokio-io/src/codec/decoder.rs index cd5777dea..f4c2d2cf6 100644 --- a/tokio-io/src/codec/decoder.rs +++ b/tokio-io/src/codec/decoder.rs @@ -1,11 +1,9 @@ +use super::encoder::Encoder; +use crate::_tokio_codec::Framed; +use crate::{AsyncRead, AsyncWrite}; use bytes::BytesMut; use std::io; -use super::encoder::Encoder; -use {AsyncRead, AsyncWrite}; - -use _tokio_codec::Framed; - /// Decoding of frames via buffers. /// /// This trait is used when constructing an instance of `Framed` or diff --git a/tokio-io/src/codec/lines_codec.rs b/tokio-io/src/codec/lines_codec.rs index 818397fa5..650489119 100644 --- a/tokio-io/src/codec/lines_codec.rs +++ b/tokio-io/src/codec/lines_codec.rs @@ -1,7 +1,7 @@ #![allow(deprecated)] +use crate::codec::{Decoder, Encoder}; use bytes::{BufMut, BytesMut}; -use codec::{Decoder, Encoder}; use std::{io, str}; /// A simple `Codec` implementation that splits up data into lines. diff --git a/tokio-io/src/codec/mod.rs b/tokio-io/src/codec/mod.rs index 663682175..20bac0827 100644 --- a/tokio-io/src/codec/mod.rs +++ b/tokio-io/src/codec/mod.rs @@ -27,10 +27,9 @@ pub use self::bytes_codec::BytesCodec; pub use self::decoder::Decoder; pub use self::encoder::Encoder; pub use self::lines_codec::LinesCodec; - -pub use framed::{Framed, FramedParts}; -pub use framed_read::FramedRead; -pub use framed_write::FramedWrite; +pub use crate::framed::{Framed, FramedParts}; +pub use crate::framed_read::FramedRead; +pub use crate::framed_write::FramedWrite; #[deprecated(since = "0.1.8", note = "Moved to tokio-codec")] #[doc(hidden)] @@ -74,10 +73,6 @@ pub mod length_delimited { //! Specifically, given the following: //! //! ``` - //! # extern crate tokio_io; - //! # extern crate bytes; - //! # extern crate futures; - //! # //! use tokio_io::{AsyncRead, AsyncWrite}; //! use tokio_io::codec::length_delimited; //! use bytes::BytesMut; @@ -89,8 +84,6 @@ pub mod length_delimited { //! //! transport.send(frame).wait().unwrap(); //! } - //! # - //! # pub fn main() {} //! ``` //! //! The encoded frame will look like this: @@ -115,8 +108,9 @@ pub mod length_delimited { //! frame head in the yielded `BytesMut`. //! //! ``` - //! # use tokio_io::AsyncRead; - //! # use tokio_io::codec::length_delimited; + //! use tokio_io::AsyncRead; + //! use tokio_io::codec::length_delimited; + //! //! # fn bind_read(io: T) { //! length_delimited::Builder::new() //! .length_field_offset(0) // default value @@ -148,8 +142,9 @@ pub mod length_delimited { //! frame head in the yielded `BytesMut`. //! //! ``` - //! # use tokio_io::AsyncRead; - //! # use tokio_io::codec::length_delimited; + //! use tokio_io::AsyncRead; + //! use tokio_io::codec::length_delimited; + //! //! # fn bind_read(io: T) { //! length_delimited::Builder::new() //! .length_field_offset(0) // default value @@ -179,8 +174,9 @@ pub mod length_delimited { //! **includes** the frame head length. //! //! ``` - //! # use tokio_io::AsyncRead; - //! # use tokio_io::codec::length_delimited; + //! use tokio_io::AsyncRead; + //! use tokio_io::codec::length_delimited; + //! //! # fn bind_read(io: T) { //! length_delimited::Builder::new() //! .length_field_offset(0) // default value @@ -212,8 +208,9 @@ pub mod length_delimited { //! frame head, including the frame head in the yielded `BytesMut`. //! //! ``` - //! # use tokio_io::AsyncRead; - //! # use tokio_io::codec::length_delimited; + //! use tokio_io::AsyncRead; + //! use tokio_io::codec::length_delimited; + //! //! # fn bind_read(io: T) { //! length_delimited::Builder::new() //! .length_field_offset(0) // default value @@ -255,8 +252,9 @@ pub mod length_delimited { //! included. //! //! ``` - //! # use tokio_io::AsyncRead; - //! # use tokio_io::codec::length_delimited; + //! use tokio_io::AsyncRead; + //! use tokio_io::codec::length_delimited; + //! //! # fn bind_read(io: T) { //! length_delimited::Builder::new() //! .length_field_offset(1) // length of hdr1 @@ -300,8 +298,9 @@ pub mod length_delimited { //! length. //! //! ``` - //! # use tokio_io::AsyncRead; - //! # use tokio_io::codec::length_delimited; + //! use tokio_io::AsyncRead; + //! use tokio_io::codec::length_delimited; + //! //! # fn bind_read(io: T) { //! length_delimited::Builder::new() //! .length_field_offset(1) // length of hdr1 @@ -345,18 +344,16 @@ pub mod length_delimited { //! configuration: //! //! ``` - //! # extern crate tokio_io; - //! # extern crate bytes; - //! # use tokio_io::AsyncWrite; - //! # use tokio_io::codec::length_delimited; - //! # use bytes::BytesMut; + //! use tokio_io::AsyncWrite; + //! use tokio_io::codec::length_delimited; + //! use bytes::BytesMut; + //! //! # fn write_frame(io: T) { //! # let _: length_delimited::FramedWrite = //! length_delimited::Builder::new() //! .length_field_length(2) //! .new_write(io); //! # } - //! # pub fn main() {} //! ``` //! //! A payload of `hello world` will be encoded as: @@ -374,5 +371,5 @@ pub mod length_delimited { //! [`Encoder`]: ../trait.Encoder.html //! [`BytesMut`]: https://docs.rs/bytes/0.4/bytes/struct.BytesMut.html - pub use length_delimited::*; + pub use crate::length_delimited::*; } diff --git a/tokio-io/src/framed.rs b/tokio-io/src/framed.rs index aea7b5468..9764e1f44 100644 --- a/tokio-io/src/framed.rs +++ b/tokio-io/src/framed.rs @@ -1,15 +1,13 @@ #![allow(deprecated)] -use std::fmt; -use std::io::{self, Read, Write}; - -use codec::{Decoder, Encoder}; -use framed_read::{framed_read2, framed_read2_with_buffer, FramedRead2}; -use framed_write::{framed_write2, framed_write2_with_buffer, FramedWrite2}; -use {AsyncRead, AsyncWrite}; - +use crate::codec::{Decoder, Encoder}; +use crate::framed_read::{framed_read2, framed_read2_with_buffer, FramedRead2}; +use crate::framed_write::{framed_write2, framed_write2_with_buffer, FramedWrite2}; +use crate::{AsyncRead, AsyncWrite}; use bytes::BytesMut; use futures::{Poll, Sink, StartSend, Stream}; +use std::fmt; +use std::io::{self, Read, Write}; /// A unified `Stream` and `Sink` interface to an underlying I/O object, using /// the `Encoder` and `Decoder` traits to encode and decode frames. @@ -174,7 +172,7 @@ where T: fmt::Debug, U: fmt::Debug, { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Framed") .field("io", &self.inner.get_ref().get_ref().0) .field("codec", &self.inner.get_ref().get_ref().1) diff --git a/tokio-io/src/framed_read.rs b/tokio-io/src/framed_read.rs index d675084b0..911af1509 100644 --- a/tokio-io/src/framed_read.rs +++ b/tokio-io/src/framed_read.rs @@ -1,13 +1,12 @@ #![allow(deprecated)] -use std::fmt; - -use codec::Decoder; -use framed::Fuse; -use AsyncRead; - +use crate::codec::Decoder; +use crate::framed::Fuse; +use crate::AsyncRead; use bytes::BytesMut; -use futures::{Async, Poll, Sink, StartSend, Stream}; +use futures::{try_ready, Async, Poll, Sink, StartSend, Stream}; +use log::trace; +use std::fmt; /// A `Stream` of messages decoded from an `AsyncRead`. #[deprecated(since = "0.1.7", note = "Moved to tokio-codec")] @@ -121,7 +120,7 @@ where T: fmt::Debug, D: fmt::Debug, { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("FramedRead") .field("inner", &self.inner.inner.0) .field("decoder", &self.inner.inner.1) diff --git a/tokio-io/src/framed_write.rs b/tokio-io/src/framed_write.rs index 483b9fac8..34b3330b9 100644 --- a/tokio-io/src/framed_write.rs +++ b/tokio-io/src/framed_write.rs @@ -1,15 +1,14 @@ #![allow(deprecated)] +use crate::codec::{Decoder, Encoder}; +use crate::framed::Fuse; +use crate::{AsyncRead, AsyncWrite}; +use bytes::BytesMut; +use futures::{try_ready, Async, AsyncSink, Poll, Sink, StartSend, Stream}; +use log::trace; use std::fmt; use std::io::{self, Read}; -use codec::{Decoder, Encoder}; -use framed::Fuse; -use {AsyncRead, AsyncWrite}; - -use bytes::BytesMut; -use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; - /// A `Sink` of frames encoded to an `AsyncWrite`. #[deprecated(since = "0.1.7", note = "Moved to tokio-codec")] #[doc(hidden)] @@ -119,7 +118,7 @@ where T: fmt::Debug, U: fmt::Debug, { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("FramedWrite") .field("inner", &self.inner.get_ref().0) .field("encoder", &self.inner.get_ref().1) diff --git a/tokio-io/src/io/copy.rs b/tokio-io/src/io/copy.rs index e8a1dac95..369800db9 100644 --- a/tokio-io/src/io/copy.rs +++ b/tokio-io/src/io/copy.rs @@ -1,9 +1,7 @@ +use crate::{AsyncRead, AsyncWrite}; +use futures::{try_ready, Future, Poll}; use std::io; -use futures::{Future, Poll}; - -use {AsyncRead, AsyncWrite}; - /// A future which will copy all data from a reader into a writer. /// /// Created by the [`copy`] function, this future will resolve to the number of diff --git a/tokio-io/src/io/flush.rs b/tokio-io/src/io/flush.rs index febc7ee1b..5001d680d 100644 --- a/tokio-io/src/io/flush.rs +++ b/tokio-io/src/io/flush.rs @@ -1,9 +1,7 @@ +use crate::AsyncWrite; +use futures::{try_ready, Async, Future, Poll}; use std::io; -use futures::{Async, Future, Poll}; - -use AsyncWrite; - /// A future used to fully flush an I/O object. /// /// Resolves to the underlying I/O object once the flush operation is complete. diff --git a/tokio-io/src/io/mod.rs b/tokio-io/src/io/mod.rs index 763cfaee7..ebda8ecab 100644 --- a/tokio-io/src/io/mod.rs +++ b/tokio-io/src/io/mod.rs @@ -26,7 +26,7 @@ pub use self::read_to_end::{read_to_end, ReadToEnd}; pub use self::read_until::{read_until, ReadUntil}; pub use self::shutdown::{shutdown, Shutdown}; pub use self::write_all::{write_all, WriteAll}; -pub use allow_std::AllowStdIo; -pub use lines::{lines, Lines}; -pub use split::{ReadHalf, WriteHalf}; -pub use window::Window; +pub use crate::allow_std::AllowStdIo; +pub use crate::lines::{lines, Lines}; +pub use crate::split::{ReadHalf, WriteHalf}; +pub use crate::window::Window; diff --git a/tokio-io/src/io/read.rs b/tokio-io/src/io/read.rs index 632cef4d2..7731256d0 100644 --- a/tokio-io/src/io/read.rs +++ b/tokio-io/src/io/read.rs @@ -1,10 +1,8 @@ +use crate::AsyncRead; +use futures::{try_ready, Future, Poll}; use std::io; use std::mem; -use futures::{Future, Poll}; - -use AsyncRead; - #[derive(Debug)] enum State { Pending { rd: R, buf: T }, diff --git a/tokio-io/src/io/read_exact.rs b/tokio-io/src/io/read_exact.rs index 3b98621ae..43e8bc0a1 100644 --- a/tokio-io/src/io/read_exact.rs +++ b/tokio-io/src/io/read_exact.rs @@ -1,10 +1,8 @@ +use crate::AsyncRead; +use futures::{try_ready, Future, Poll}; use std::io; use std::mem; -use futures::{Future, Poll}; - -use AsyncRead; - /// A future which can be used to easily read exactly enough bytes to fill /// a buffer. /// diff --git a/tokio-io/src/io/read_to_end.rs b/tokio-io/src/io/read_to_end.rs index 296af6e30..8f65eb534 100644 --- a/tokio-io/src/io/read_to_end.rs +++ b/tokio-io/src/io/read_to_end.rs @@ -1,10 +1,8 @@ +use crate::AsyncRead; +use futures::{Future, Poll}; use std::io; use std::mem; -use futures::{Future, Poll}; - -use AsyncRead; - /// A future which can be used to easily read the entire contents of a stream /// into a vector. /// diff --git a/tokio-io/src/io/read_until.rs b/tokio-io/src/io/read_until.rs index d0be4c944..4d7165cc5 100644 --- a/tokio-io/src/io/read_until.rs +++ b/tokio-io/src/io/read_until.rs @@ -1,10 +1,8 @@ +use crate::AsyncRead; +use futures::{Future, Poll}; use std::io::{self, BufRead}; use std::mem; -use futures::{Future, Poll}; - -use AsyncRead; - /// A future which can be used to easily read the contents of a stream into a /// vector until the delimiter is reached. /// diff --git a/tokio-io/src/io/shutdown.rs b/tokio-io/src/io/shutdown.rs index d963a813a..a7e092c0a 100644 --- a/tokio-io/src/io/shutdown.rs +++ b/tokio-io/src/io/shutdown.rs @@ -1,9 +1,7 @@ +use crate::AsyncWrite; +use futures::{try_ready, Async, Future, Poll}; use std::io; -use futures::{Async, Future, Poll}; - -use AsyncWrite; - /// A future used to fully shutdown an I/O object. /// /// Resolves to the underlying I/O object once the shutdown operation is diff --git a/tokio-io/src/io/write_all.rs b/tokio-io/src/io/write_all.rs index ba8af4a22..6867a193f 100644 --- a/tokio-io/src/io/write_all.rs +++ b/tokio-io/src/io/write_all.rs @@ -1,10 +1,8 @@ +use crate::AsyncWrite; +use futures::{try_ready, Future, Poll}; use std::io; use std::mem; -use futures::{Future, Poll}; - -use AsyncWrite; - /// A future used to write the entire contents of some data to a stream. /// /// This is created by the [`write_all`] top-level method. diff --git a/tokio-io/src/length_delimited.rs b/tokio-io/src/length_delimited.rs index c211c9535..99d271807 100644 --- a/tokio-io/src/length_delimited.rs +++ b/tokio-io/src/length_delimited.rs @@ -1,12 +1,9 @@ #![allow(deprecated)] -use {codec, AsyncRead, AsyncWrite}; - +use crate::{codec, AsyncRead, AsyncWrite}; use bytes::buf::Chain; use bytes::{Buf, BufMut, BytesMut, IntoBuf}; - -use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; - +use futures::{try_ready, Async, AsyncSink, Poll, Sink, StartSend, Stream}; use std::error::Error as StdError; use std::io::{self, Cursor}; use std::{cmp, fmt}; @@ -174,7 +171,7 @@ where T: fmt::Debug, B::Buf: fmt::Debug, { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Framed") .field("inner", &self.inner) .finish() @@ -580,7 +577,7 @@ where T: fmt::Debug, B::Buf: fmt::Debug, { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("FramedWrite") .field("inner", &self.inner) .field("builder", &self.builder) @@ -859,18 +856,16 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio_io; - /// # extern crate bytes; - /// # use tokio_io::AsyncWrite; - /// # use tokio_io::codec::length_delimited; - /// # use bytes::BytesMut; + /// use tokio_io::AsyncWrite; + /// use tokio_io::codec::length_delimited; + /// use bytes::BytesMut; + /// /// # fn write_frame(io: T) { /// # let _: length_delimited::FramedWrite = /// length_delimited::Builder::new() /// .length_field_length(2) /// .new_write(io); /// # } - /// # pub fn main() {} /// ``` pub fn new_write(&self, inner: T) -> FramedWrite where @@ -889,18 +884,16 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio_io; - /// # extern crate bytes; - /// # use tokio_io::{AsyncRead, AsyncWrite}; - /// # use tokio_io::codec::length_delimited; - /// # use bytes::BytesMut; + /// use tokio_io::{AsyncRead, AsyncWrite}; + /// use tokio_io::codec::length_delimited; + /// use bytes::BytesMut; + /// /// # fn write_frame(io: T) { /// # let _: length_delimited::Framed = /// length_delimited::Builder::new() /// .length_field_length(2) /// .new_framed(io); /// # } - /// # pub fn main() {} /// ``` pub fn new_framed(&self, inner: T) -> Framed where @@ -925,13 +918,13 @@ impl Builder { // ===== impl FrameTooBig ===== impl fmt::Debug for FrameTooBig { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("FrameTooBig").finish() } } impl fmt::Display for FrameTooBig { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.description()) } } diff --git a/tokio-io/src/lib.rs b/tokio-io/src/lib.rs index 090366407..d0fe8af85 100644 --- a/tokio-io/src/lib.rs +++ b/tokio-io/src/lib.rs @@ -1,5 +1,7 @@ -#![deny(missing_docs, missing_debug_implementations, warnings)] #![doc(html_root_url = "https://docs.rs/tokio-io/0.1.12")] +#![deny(missing_debug_implementations, missing_docs, rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! Core I/O traits and combinators when working with Tokio. //! @@ -9,22 +11,14 @@ //! [found online]: https://tokio.rs/docs/getting-started/core/ //! [low level details]: https://tokio.rs/docs/going-deeper-tokio/core-low-level/ -#[macro_use] -extern crate log; - -#[macro_use] -extern crate futures; -extern crate bytes; - +use futures::{Future, Stream}; use std::io as std_io; -use futures::{Future, Stream}; - /// A convenience typedef around a `Future` whose error component is `io::Error` -pub type IoFuture = Box + Send>; +pub type IoFuture = Box + Send>; /// A convenience typedef around a `Stream` whose error component is `io::Error` -pub type IoStream = Box + Send>; +pub type IoStream = Box + Send>; /// A convenience macro for working with `io::Result` from the `Read` and /// `Write` traits. @@ -65,6 +59,6 @@ pub use self::async_write::AsyncWrite; fn _assert_objects() { fn _assert() {} - _assert::>(); - _assert::>(); + _assert::>(); + _assert::>(); } diff --git a/tokio-io/src/lines.rs b/tokio-io/src/lines.rs index 8e59ff8fa..ebe1ed5ea 100644 --- a/tokio-io/src/lines.rs +++ b/tokio-io/src/lines.rs @@ -1,10 +1,8 @@ +use crate::AsyncRead; +use futures::{Poll, Stream}; use std::io::{self, BufRead}; use std::mem; -use futures::{Poll, Stream}; - -use AsyncRead; - /// Combinator created by the top-level `lines` method which is a stream over /// the lines of text on an I/O object. #[derive(Debug)] diff --git a/tokio-io/src/split.rs b/tokio-io/src/split.rs index ef8f990c8..b9bd326ba 100644 --- a/tokio-io/src/split.rs +++ b/tokio-io/src/split.rs @@ -1,10 +1,8 @@ -use std::io::{self, Read, Write}; - +use crate::{AsyncRead, AsyncWrite}; use bytes::{Buf, BufMut}; use futures::sync::BiLock; -use futures::{Async, Poll}; - -use {AsyncRead, AsyncWrite}; +use futures::{try_ready, Async, Poll}; +use std::io::{self, Read, Write}; /// The readable half of an object returned from `AsyncRead::split`. #[derive(Debug)] @@ -112,14 +110,12 @@ fn wrap_as_io(t: Async) -> Result, io::Error> { #[cfg(test)] mod tests { - extern crate tokio_current_thread; - use super::{AsyncRead, AsyncWrite, ReadHalf, WriteHalf}; use bytes::{BytesMut, IntoBuf}; use futures::sync::BiLock; use futures::{future::lazy, future::ok, Async, Poll}; - use std::io::{self, Read, Write}; + use tokio_current_thread; struct RW; diff --git a/tokio-io/tests/async_read.rs b/tokio-io/tests/async_read.rs index 604e99fd4..430c935ea 100644 --- a/tokio-io/tests/async_read.rs +++ b/tokio-io/tests/async_read.rs @@ -1,12 +1,7 @@ -extern crate bytes; -extern crate futures; -extern crate tokio_io; - use bytes::{BufMut, BytesMut}; use futures::Async; -use tokio_io::AsyncRead; - use std::io::{self, Read}; +use tokio_io::AsyncRead; #[test] fn read_buf_success() { diff --git a/tokio-io/tests/length_delimited.rs b/tokio-io/tests/length_delimited.rs index c99bbf089..d217a178a 100644 --- a/tokio-io/tests/length_delimited.rs +++ b/tokio-io/tests/length_delimited.rs @@ -1,17 +1,12 @@ // This file is testing deprecated code. #![allow(deprecated)] -extern crate futures; -extern crate tokio_io; - -use tokio_io::codec::length_delimited::*; -use tokio_io::{AsyncRead, AsyncWrite}; - use futures::Async::*; use futures::{Poll, Sink, Stream}; - use std::collections::VecDeque; use std::io; +use tokio_io::codec::length_delimited::*; +use tokio_io::{AsyncRead, AsyncWrite}; macro_rules! mock { ($($x:expr,)*) => {{ diff --git a/tokio-macros/Cargo.toml b/tokio-macros/Cargo.toml index 9e4b6f8bb..46a378565 100644 --- a/tokio-macros/Cargo.toml +++ b/tokio-macros/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "tokio-macros" version = "0.1.0" -authors = ["Tokio Contributors "] edition = "2018" +authors = ["Tokio Contributors "] publish = false [lib] diff --git a/tokio-macros/src/lib.rs b/tokio-macros/src/lib.rs index d501f743b..eafed6dd7 100644 --- a/tokio-macros/src/lib.rs +++ b/tokio-macros/src/lib.rs @@ -1,4 +1,9 @@ #![cfg(feature = "async-await-preview")] +#![deny(missing_debug_implementations, unreachable_pub, rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] + +//! Macros for use with Tokio extern crate proc_macro; diff --git a/tokio-reactor/Cargo.toml b/tokio-reactor/Cargo.toml index 0975ac5b9..409bd39fc 100644 --- a/tokio-reactor/Cargo.toml +++ b/tokio-reactor/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-reactor" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.1.x" git tag. -version = "0.1.9" +# - Create "v0.2.x" git tag. +version = "0.2.0" +edition = "2018" authors = ["Carl Lerche "] license = "MIT" readme = "README.md" @@ -19,6 +20,7 @@ description = """ Event loop that drives Tokio I/O resources. """ categories = ["asynchronous", "network-programming"] +publish = false [dependencies] crossbeam-utils = "0.6.0" @@ -29,9 +31,9 @@ mio = "0.6.14" num_cpus = "1.8.0" parking_lot = "0.7.0" slab = "0.4.0" -tokio-executor = "0.1.1" -tokio-io = "0.1.6" -tokio-sync = "0.1.1" +tokio-executor = { version = "0.2.0", path = "../tokio-executor" } +tokio-io = { version = "0.2.0", path = "../tokio-io" } +tokio-sync = { version = "0.2.0", path = "../tokio-sync" } [dev-dependencies] num_cpus = "1.8.0" diff --git a/tokio-reactor/benches/basic.rs b/tokio-reactor/benches/basic.rs index 63020d2f7..a126d1330 100644 --- a/tokio-reactor/benches/basic.rs +++ b/tokio-reactor/benches/basic.rs @@ -1,13 +1,7 @@ #![feature(test)] -#![deny(warnings)] +#![deny(warnings, rust_2018_idioms)] -extern crate futures; -extern crate mio; -extern crate num_cpus; extern crate test; -extern crate tokio; -extern crate tokio_io_pool; -extern crate tokio_reactor; const NUM_YIELD: usize = 500; const TASKS_PER_CPU: usize = 100; diff --git a/tokio-reactor/src/background.rs b/tokio-reactor/src/background.rs index d4bfb78aa..70e8ebd36 100644 --- a/tokio-reactor/src/background.rs +++ b/tokio-reactor/src/background.rs @@ -1,7 +1,6 @@ -use {AtomicTask, Handle, Reactor}; - +use crate::{AtomicTask, Handle, Reactor}; use futures::{task, Async, Future, Poll}; - +use log::debug; use std::io; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; diff --git a/tokio-reactor/src/lib.rs b/tokio-reactor/src/lib.rs index 15ea8fd2d..fb8f35312 100644 --- a/tokio-reactor/src/lib.rs +++ b/tokio-reactor/src/lib.rs @@ -1,5 +1,7 @@ #![doc(html_root_url = "https://docs.rs/tokio-reactor/0.1.9")] -#![deny(missing_docs, warnings, missing_debug_implementations)] +#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! Event loop that drives Tokio I/O resources. //! @@ -30,21 +32,6 @@ //! [`PollEvented`]: struct.PollEvented.html //! [reactor module]: https://docs.rs/tokio/0.1/tokio/reactor/index.html -extern crate crossbeam_utils; -#[macro_use] -extern crate futures; -#[macro_use] -extern crate lazy_static; -#[macro_use] -extern crate log; -extern crate mio; -extern crate num_cpus; -extern crate parking_lot; -extern crate slab; -extern crate tokio_executor; -extern crate tokio_io; -extern crate tokio_sync; - pub(crate) mod background; mod poll_evented; mod registration; @@ -58,13 +45,11 @@ pub use self::registration::Registration; // ===== Private imports ===== -use sharded_rwlock::RwLock; - +use crate::sharded_rwlock::RwLock; use futures::task::Task; -use tokio_executor::park::{Park, Unpark}; -use tokio_executor::Enter; -use tokio_sync::task::AtomicTask; - +use log::{debug, log_enabled, trace, Level}; +use mio::event::Evented; +use slab::Slab; use std::cell::RefCell; use std::error::Error; use std::io; @@ -76,10 +61,9 @@ use std::sync::atomic::Ordering::{Relaxed, SeqCst}; use std::sync::{Arc, Weak}; use std::time::{Duration, Instant}; use std::{fmt, usize}; - -use log::Level; -use mio::event::Evented; -use slab::Slab; +use tokio_executor::park::{Park, Unpark}; +use tokio_executor::Enter; +use tokio_sync::task::AtomicTask; /// The core reactor, or event loop. /// @@ -467,7 +451,7 @@ impl Park for Reactor { } impl fmt::Debug for Reactor { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Reactor") } } @@ -519,7 +503,7 @@ impl Default for Handle { } impl fmt::Debug for Handle { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Handle") } } @@ -641,7 +625,7 @@ impl HandlePriv { } impl fmt::Debug for HandlePriv { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "HandlePriv") } } @@ -652,7 +636,7 @@ impl Inner { /// Register an I/O resource with the reactor. /// /// The registration token is returned. - fn add_source(&self, source: &Evented) -> io::Result { + fn add_source(&self, source: &dyn Evented) -> io::Result { // Get an ABA guard value let aba_guard = self.next_aba_guard.fetch_add(1 << TOKEN_SHIFT, Relaxed); @@ -690,7 +674,7 @@ impl Inner { } /// Deregisters an I/O resource from the reactor. - fn deregister_source(&self, source: &Evented) -> io::Result<()> { + fn deregister_source(&self, source: &dyn Evented) -> io::Result<()> { self.io.deregister(source) } @@ -773,7 +757,7 @@ mod platform { // ===== impl SetFallbackError ===== impl fmt::Display for SetFallbackError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{}", self.description()) } } diff --git a/tokio-reactor/src/poll_evented.rs b/tokio-reactor/src/poll_evented.rs index 230f7c342..140ac4caf 100644 --- a/tokio-reactor/src/poll_evented.rs +++ b/tokio-reactor/src/poll_evented.rs @@ -1,14 +1,12 @@ -use {Handle, Registration}; - -use futures::{task, Async, Poll}; +use crate::{Handle, Registration}; +use futures::{task, try_ready, Async, Poll}; use mio; use mio::event::Evented; -use tokio_io::{AsyncRead, AsyncWrite}; - use std::fmt; use std::io::{self, Read, Write}; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::Relaxed; +use tokio_io::{AsyncRead, AsyncWrite}; /// Associates an I/O resource that implements the [`std::io::Read`] and/or /// [`std::io::Write`] traits with the reactor that drives it. @@ -108,7 +106,7 @@ macro_rules! poll_ready { // Load cached & encoded readiness. let mut cached = $me.inner.$cache.load(Relaxed); - let mask = $mask | ::platform::hup(); + let mask = $mask | crate::platform::hup(); // See if the current readiness matches any bits. let mut ret = mio::Ready::from_usize(cached) & $mask; @@ -248,7 +246,10 @@ where pub fn clear_read_ready(&self, ready: mio::Ready) -> io::Result<()> { // Cannot clear write readiness assert!(!ready.is_writable(), "cannot clear write readiness"); - assert!(!::platform::is_hup(&ready), "cannot clear HUP readiness"); + assert!( + !crate::platform::is_hup(&ready), + "cannot clear HUP readiness" + ); self.inner .read_readiness @@ -473,7 +474,7 @@ fn is_wouldblock(r: &io::Result) -> bool { } impl fmt::Debug for PollEvented { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PollEvented").field("io", &self.io).finish() } } diff --git a/tokio-reactor/src/registration.rs b/tokio-reactor/src/registration.rs index 4ad9f0861..3b7e8391b 100644 --- a/tokio-reactor/src/registration.rs +++ b/tokio-reactor/src/registration.rs @@ -1,8 +1,7 @@ -use {Direction, Handle, HandlePriv, Task}; - +use crate::{Direction, Handle, HandlePriv, Task}; use futures::{task, Async, Poll}; +use log::debug; use mio::{self, Evented}; - use std::cell::UnsafeCell; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; @@ -498,7 +497,7 @@ impl Inner { }; let mask = direction.mask(); - let mask_no_hup = (mask - ::platform::hup()).as_usize(); + let mask_no_hup = (mask - crate::platform::hup()).as_usize(); let io_dispatch = inner.io_dispatch.read(); let sched = &io_dispatch[self.token]; diff --git a/tokio-reactor/src/sharded_rwlock.rs b/tokio-reactor/src/sharded_rwlock.rs index 6b6207b59..ec16fb13c 100644 --- a/tokio-reactor/src/sharded_rwlock.rs +++ b/tokio-reactor/src/sharded_rwlock.rs @@ -4,6 +4,10 @@ //! while making write operations slower. It also incurs much higher memory overhead than //! traditional reader-writer locks. +use crossbeam_utils::CachePadded; +use lazy_static::lazy_static; +use num_cpus; +use parking_lot; use std::cell::UnsafeCell; use std::collections::HashMap; use std::marker::PhantomData; @@ -12,10 +16,6 @@ use std::ops::{Deref, DerefMut}; use std::sync::Mutex; use std::thread::{self, ThreadId}; -use crossbeam_utils::CachePadded; -use num_cpus; -use parking_lot; - /// A scalable read-writer lock. /// /// This type of lock allows a number of readers or at most one writer at any point in time. The @@ -65,7 +65,7 @@ impl RwLock { /// or writers will acquire the lock first. /// /// Returns an RAII guard which will release this thread's shared access once it is dropped. - pub fn read(&self) -> RwLockReadGuard { + pub fn read(&self) -> RwLockReadGuard<'_, T> { // Take the current thread index and map it to a shard index. Thread indices will tend to // distribute shards among threads equally, thus reducing contention due to read-locking. let shard_index = thread_index() & (self.shards.len() - 1); @@ -84,7 +84,7 @@ impl RwLock { /// the lock. /// /// Returns an RAII guard which will drop the write access of this rwlock when dropped. - pub fn write(&self) -> RwLockWriteGuard { + pub fn write(&self) -> RwLockWriteGuard<'_, T> { // Write-lock each shard in succession. for shard in &self.shards { // The write guard is forgotten, but the lock will be manually unlocked in `drop`. @@ -99,7 +99,7 @@ impl RwLock { } /// A guard used to release the shared read access of a `RwLock` when dropped. -pub struct RwLockReadGuard<'a, T: 'a> { +pub struct RwLockReadGuard<'a, T> { parent: &'a RwLock, _guard: parking_lot::RwLockReadGuard<'a, ()>, _marker: PhantomData>, @@ -116,7 +116,7 @@ impl<'a, T> Deref for RwLockReadGuard<'a, T> { } /// A guard used to release the exclusive write access of a `RwLock` when dropped. -pub struct RwLockWriteGuard<'a, T: 'a> { +pub struct RwLockWriteGuard<'a, T> { parent: &'a RwLock, _marker: PhantomData>, } diff --git a/tokio-signal/Cargo.toml b/tokio-signal/Cargo.toml index 0b2b9e191..ceffa126a 100644 --- a/tokio-signal/Cargo.toml +++ b/tokio-signal/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-signal" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.2.x" git tag. -version = "0.2.8" +# - Create "v0.3.x" git tag. +version = "0.3.0" +edition = "2018" authors = ["Tokio Contributors "] license = "MIT" repository = "https://github.com/tokio-rs/tokio" @@ -18,6 +19,7 @@ description = """ An implementation of an asynchronous Unix signal handling backed futures. """ categories = ["asynchronous"] +publish = false [badges] travis-ci = { repository = "tokio-rs/tokio" } @@ -26,9 +28,9 @@ appveyor = { repository = "carllerche/tokio", id = "s83yxhy9qeb58va7" } [dependencies] futures = "0.1.11" mio = "0.6.14" -tokio-reactor = "0.1.0" -tokio-executor = "0.1.0" -tokio-io = "0.1" +tokio-reactor = { version = "0.2.0", path = "../tokio-reactor" } +tokio-executor = { version = "0.2.0", path = "../tokio-executor" } +tokio-io = { version = "0.2.0", path = "../tokio-io" } [target.'cfg(unix)'.dependencies] libc = "0.2" @@ -36,7 +38,7 @@ mio-uds = "0.6" signal-hook-registry = "~1" [dev-dependencies] -tokio = "0.1.8" +tokio = { version = "0.2.0", path = "../tokio" } [target.'cfg(windows)'.dependencies.winapi] version = "0.3" diff --git a/tokio-signal/README.md b/tokio-signal/README.md index e368fb44b..695394fed 100644 --- a/tokio-signal/README.md +++ b/tokio-signal/README.md @@ -16,10 +16,6 @@ tokio-signal = "0.2.8" Next you can use this in conjunction with the `tokio` and `futures` crates: ```rust,no_run -extern crate futures; -extern crate tokio; -extern crate tokio_signal; - use futures::{Future, Stream}; fn main() { diff --git a/tokio-signal/examples/ctrl-c.rs b/tokio-signal/examples/ctrl-c.rs index 6d6adfd76..a05e26254 100644 --- a/tokio-signal/examples/ctrl-c.rs +++ b/tokio-signal/examples/ctrl-c.rs @@ -1,13 +1,14 @@ -extern crate futures; -extern crate tokio; -extern crate tokio_signal; +#![deny(warnings, rust_2018_idioms)] + +use tokio; +use tokio_signal; use futures::{Future, Stream}; /// how many signals to handle before exiting const STOP_AFTER: u64 = 10; -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { // tokio_signal provides a convenience builder for Ctrl+C // this even works cross-platform: linux and windows! // diff --git a/tokio-signal/examples/multiple.rs b/tokio-signal/examples/multiple.rs index fa8f1be25..c0443ce7e 100644 --- a/tokio-signal/examples/multiple.rs +++ b/tokio-signal/examples/multiple.rs @@ -1,8 +1,6 @@ -//! A small example of how to listen for two signals at the same time +#![deny(warnings, rust_2018_idioms)] -extern crate futures; -extern crate tokio; -extern crate tokio_signal; +//! A small example of how to listen for two signals at the same time // A trick to not fail build on non-unix platforms when using unix-specific features. #[cfg(unix)] @@ -11,7 +9,7 @@ mod platform { use futures::{Future, Stream}; use tokio_signal::unix::{Signal, SIGINT, SIGTERM}; - pub fn main() -> Result<(), Box<::std::error::Error>> { + pub fn main() -> Result<(), Box> { // Create a stream for each of the signals we'd like to handle. let sigint = Signal::new(SIGINT).flatten_stream(); let sigterm = Signal::new(SIGTERM).flatten_stream(); @@ -44,11 +42,11 @@ mod platform { #[cfg(not(unix))] mod platform { - pub fn main() -> Result<(), Box<::std::error::Error>> { + pub fn main() -> Result<(), Box> { Ok(()) } } -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { platform::main() } diff --git a/tokio-signal/examples/sighup-example.rs b/tokio-signal/examples/sighup-example.rs index 5edb78624..983469121 100644 --- a/tokio-signal/examples/sighup-example.rs +++ b/tokio-signal/examples/sighup-example.rs @@ -1,6 +1,4 @@ -extern crate futures; -extern crate tokio; -extern crate tokio_signal; +#![deny(warnings, rust_2018_idioms)] // A trick to not fail build on non-unix platforms when using unix-specific features. #[cfg(unix)] @@ -9,7 +7,7 @@ mod platform { use futures::{Future, Stream}; use tokio_signal::unix::{Signal, SIGHUP}; - pub fn main() -> Result<(), Box<::std::error::Error>> { + pub fn main() -> Result<(), Box> { // on Unix, we can listen to whatever signal we want, in this case: SIGHUP let stream = Signal::new(SIGHUP).flatten_stream(); @@ -43,11 +41,11 @@ mod platform { #[cfg(not(unix))] mod platform { - pub fn main() -> Result<(), Box<::std::error::Error>> { + pub fn main() -> Result<(), Box> { Ok(()) } } -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { platform::main() } diff --git a/tokio-signal/src/lib.rs b/tokio-signal/src/lib.rs index 1a33ec789..2e73dd2a8 100644 --- a/tokio-signal/src/lib.rs +++ b/tokio-signal/src/lib.rs @@ -1,5 +1,7 @@ #![doc(html_root_url = "https://docs.rs/tokio-signal/0.2.8")] -#![deny(missing_docs)] +#![deny(missing_docs, rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! Asynchronous signal handling for Tokio //! @@ -21,74 +23,49 @@ //! Print out all ctrl-C notifications received //! //! ```rust,no_run -//! extern crate futures; -//! extern crate tokio; -//! extern crate tokio_signal; -//! //! use futures::{Future, Stream}; //! -//! fn main() { -//! // Create an infinite stream of "Ctrl+C" notifications. Each item received -//! // on this stream may represent multiple ctrl-c signals. -//! let ctrl_c = tokio_signal::ctrl_c().flatten_stream(); +//! // Create an infinite stream of "Ctrl+C" notifications. Each item received +//! // on this stream may represent multiple ctrl-c signals. +//! let ctrl_c = tokio_signal::ctrl_c().flatten_stream(); //! -//! // Process each ctrl-c as it comes in -//! let prog = ctrl_c.for_each(|()| { -//! println!("ctrl-c received!"); -//! Ok(()) -//! }); +//! // Process each ctrl-c as it comes in +//! let prog = ctrl_c.for_each(|()| { +//! println!("ctrl-c received!"); +//! Ok(()) +//! }); //! -//! tokio::runtime::current_thread::block_on_all(prog).unwrap(); -//! } +//! tokio::runtime::current_thread::block_on_all(prog).unwrap(); //! ``` //! //! Wait for SIGHUP on Unix //! //! ```rust,no_run -//! # extern crate futures; -//! # extern crate tokio; -//! # extern crate tokio_signal; -//! # #[cfg(unix)] -//! # mod foo { -//! # -//! extern crate futures; -//! extern crate tokio; -//! extern crate tokio_signal; -//! +//! # #[cfg(unix)] fn dox() { //! use futures::{Future, Stream}; //! use tokio_signal::unix::{Signal, SIGHUP}; //! -//! fn main() { -//! // Like the previous example, this is an infinite stream of signals -//! // being received, and signals may be coalesced while pending. -//! let stream = Signal::new(SIGHUP).flatten_stream(); +//! // Like the previous example, this is an infinite stream of signals +//! // being received, and signals may be coalesced while pending. +//! let stream = Signal::new(SIGHUP).flatten_stream(); //! -//! // Convert out stream into a future and block the program -//! tokio::runtime::current_thread::block_on_all(stream.into_future()).ok().unwrap(); -//! } +//! // Convert out stream into a future and block the program +//! tokio::runtime::current_thread::block_on_all(stream.into_future()).ok().unwrap(); //! # } -//! # fn main() {} //! ``` -extern crate futures; -extern crate mio; -extern crate tokio_executor; -extern crate tokio_io; -extern crate tokio_reactor; - -use std::io; - use futures::stream::Stream; use futures::{future, Future}; +use std::io; use tokio_reactor::Handle; pub mod unix; pub mod windows; /// A future whose error is `io::Error` -pub type IoFuture = Box + Send>; +pub type IoFuture = Box + Send>; /// A stream whose error is `io::Error` -pub type IoStream = Box + Send>; +pub type IoStream = Box + Send>; /// Creates a stream which receives "ctrl-c" notifications sent to a process. /// @@ -125,7 +102,7 @@ pub fn ctrl_c_handle(handle: &Handle) -> IoFuture> { let handle = handle.clone(); Box::new(future::lazy(move || { unix::Signal::with_handle(unix::libc::SIGINT, &handle) - .map(|x| Box::new(x.map(|_| ())) as Box + Send>) + .map(|x| Box::new(x.map(|_| ())) as Box + Send>) })) } @@ -135,7 +112,7 @@ pub fn ctrl_c_handle(handle: &Handle) -> IoFuture> { // Use lazy to ensure that `ctrl_c` gets called while on an event loop Box::new(future::lazy(move || { windows::Event::ctrl_c_handle(&handle) - .map(|x| Box::new(x) as Box + Send>) + .map(|x| Box::new(x) as Box + Send>) })) } } diff --git a/tokio-signal/src/unix.rs b/tokio-signal/src/unix.rs index 27502fc07..3982ebec2 100644 --- a/tokio-signal/src/unix.rs +++ b/tokio-signal/src/unix.rs @@ -5,27 +5,24 @@ #![cfg(unix)] -pub extern crate libc; -extern crate mio; -extern crate mio_uds; -extern crate signal_hook_registry; +pub use libc; use std::io::prelude::*; use std::io::{self, Error, ErrorKind}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Mutex, Once, ONCE_INIT}; -use self::libc::c_int; -use self::mio_uds::UnixStream; use futures::future; use futures::sync::mpsc::{channel, Receiver, Sender}; use futures::{Async, Future}; use futures::{Poll, Stream}; +use libc::c_int; +use mio_uds::UnixStream; use tokio_io::IoFuture; use tokio_reactor::{Handle, PollEvented}; -pub use self::libc::{SIGALRM, SIGHUP, SIGPIPE, SIGQUIT, SIGTRAP}; -pub use self::libc::{SIGINT, SIGTERM, SIGUSR1, SIGUSR2}; +pub use libc::{SIGALRM, SIGHUP, SIGPIPE, SIGQUIT, SIGTRAP}; +pub use libc::{SIGINT, SIGTERM, SIGUSR1, SIGUSR2}; /// BSD-specific definitions #[cfg(any( @@ -420,7 +417,7 @@ impl Drop for Signal { #[cfg(test)] mod tests { - extern crate tokio; + use tokio; use super::*; diff --git a/tokio-signal/src/windows.rs b/tokio-signal/src/windows.rs index 8e1cd49ec..f03bbb481 100644 --- a/tokio-signal/src/windows.rs +++ b/tokio-signal/src/windows.rs @@ -7,17 +7,11 @@ #![cfg(windows)] -extern crate mio; -extern crate winapi; - use std::cell::RefCell; use std::io; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Once, ONCE_INIT}; -use self::winapi::shared::minwindef::*; -use self::winapi::um::consoleapi::SetConsoleCtrlHandler; -use self::winapi::um::wincon::*; use futures::future; use futures::stream::Fuse; use futures::sync::mpsc; @@ -25,8 +19,11 @@ use futures::sync::oneshot; use futures::{Async, Future, Poll, Stream}; use mio::Ready; use tokio_reactor::{Handle, PollEvented}; +use winapi::shared::minwindef::*; +use winapi::um::consoleapi::SetConsoleCtrlHandler; +use winapi::um::wincon::*; -use IoFuture; +use crate::IoFuture; static INIT: Once = ONCE_INIT; static mut GLOBAL_STATE: *mut GlobalState = 0 as *mut _; @@ -158,7 +155,7 @@ fn global_init(handle: &Handle) -> io::Result<()> { let ready = reg.readiness.clone(); let (tx, rx) = mpsc::unbounded(); - let reg = try!(PollEvented::new_with_handle(reg, handle)); + let reg = PollEvented::new_with_handle(reg, handle)?; unsafe { let state = Box::new(GlobalState { @@ -348,12 +345,10 @@ impl mio::Evented for MyRegistration { #[cfg(test)] mod tests { - extern crate tokio; - - use self::tokio::runtime::current_thread; - use self::tokio::timer::Timeout; use super::*; use std::time::Duration; + use tokio::runtime::current_thread; + use tokio::timer::Timeout; fn with_timeout(future: F) -> impl Future { Timeout::new(future, Duration::from_secs(1)).map_err(|e| { diff --git a/tokio-signal/tests/drop_multi_loop.rs b/tokio-signal/tests/drop_multi_loop.rs index 7228281f4..bc8214a50 100644 --- a/tokio-signal/tests/drop_multi_loop.rs +++ b/tokio-signal/tests/drop_multi_loop.rs @@ -1,9 +1,10 @@ #![cfg(unix)] +#![deny(warnings, rust_2018_idioms)] -extern crate libc; +use libc; pub mod support; -use support::*; +use crate::support::*; const TEST_SIGNAL: libc::c_int = libc::SIGUSR1; diff --git a/tokio-signal/tests/drop_then_get_a_signal.rs b/tokio-signal/tests/drop_then_get_a_signal.rs index 8b58c0c20..4530860c1 100644 --- a/tokio-signal/tests/drop_then_get_a_signal.rs +++ b/tokio-signal/tests/drop_then_get_a_signal.rs @@ -1,9 +1,10 @@ #![cfg(unix)] +#![deny(warnings, rust_2018_idioms)] -extern crate libc; +use libc; pub mod support; -use support::*; +use crate::support::*; #[test] fn drop_then_get_a_signal() { diff --git a/tokio-signal/tests/dropping_does_not_deregister_other_instances.rs b/tokio-signal/tests/dropping_does_not_deregister_other_instances.rs index 9ff289a55..39741d29d 100644 --- a/tokio-signal/tests/dropping_does_not_deregister_other_instances.rs +++ b/tokio-signal/tests/dropping_does_not_deregister_other_instances.rs @@ -1,9 +1,10 @@ #![cfg(unix)] +#![deny(warnings, rust_2018_idioms)] -extern crate libc; +use libc; pub mod support; -use support::*; +use crate::support::*; const TEST_SIGNAL: libc::c_int = libc::SIGUSR1; diff --git a/tokio-signal/tests/multi_loop.rs b/tokio-signal/tests/multi_loop.rs index 42643040e..112139f88 100644 --- a/tokio-signal/tests/multi_loop.rs +++ b/tokio-signal/tests/multi_loop.rs @@ -1,12 +1,12 @@ #![cfg(unix)] - -extern crate libc; - -use std::sync::mpsc::channel; -use std::thread; +#![deny(warnings, rust_2018_idioms)] pub mod support; -use support::*; +use crate::support::*; + +use libc; +use std::sync::mpsc::channel; +use std::thread; #[test] fn multi_loop() { diff --git a/tokio-signal/tests/notify_both.rs b/tokio-signal/tests/notify_both.rs index b147324f3..16f73d610 100644 --- a/tokio-signal/tests/notify_both.rs +++ b/tokio-signal/tests/notify_both.rs @@ -1,9 +1,10 @@ #![cfg(unix)] - -extern crate libc; +#![deny(warnings, rust_2018_idioms)] pub mod support; -use support::*; +use crate::support::*; + +use libc; #[test] fn notify_both() { diff --git a/tokio-signal/tests/signal.rs b/tokio-signal/tests/signal.rs index de47fed42..a771e53f4 100644 --- a/tokio-signal/tests/signal.rs +++ b/tokio-signal/tests/signal.rs @@ -1,9 +1,10 @@ #![cfg(unix)] - -extern crate libc; +#![deny(warnings, rust_2018_idioms)] pub mod support; -use support::*; +use crate::support::*; + +use libc; #[test] fn tokio_simple() { diff --git a/tokio-signal/tests/simple.rs b/tokio-signal/tests/simple.rs index 2d98a02ff..55a14cbd0 100644 --- a/tokio-signal/tests/simple.rs +++ b/tokio-signal/tests/simple.rs @@ -1,9 +1,10 @@ #![cfg(unix)] - -extern crate libc; +#![deny(warnings, rust_2018_idioms)] pub mod support; -use support::*; +use crate::support::*; + +use libc; #[test] fn simple() { diff --git a/tokio-signal/tests/support.rs b/tokio-signal/tests/support.rs index be0a7cda7..f7644d665 100644 --- a/tokio-signal/tests/support.rs +++ b/tokio-signal/tests/support.rs @@ -1,17 +1,13 @@ #![cfg(unix)] +#![deny(warnings, rust_2018_idioms)] -extern crate futures; -extern crate libc; -extern crate tokio; -extern crate tokio_signal; - -use self::libc::{c_int, getpid, kill}; -use self::tokio::timer::Timeout; +use libc::{c_int, getpid, kill}; use std::time::Duration; +use tokio::timer::Timeout; -pub use self::futures::{Future, Stream}; -pub use self::tokio::runtime::current_thread::{self, Runtime as CurrentThreadRuntime}; -pub use self::tokio_signal::unix::Signal; +pub use futures::{Future, Stream}; +pub use tokio::runtime::current_thread::{self, Runtime as CurrentThreadRuntime}; +pub use tokio_signal::unix::Signal; pub fn with_timeout(future: F) -> impl Future { Timeout::new(future, Duration::from_secs(1)).map_err(|e| { diff --git a/tokio-signal/tests/twice.rs b/tokio-signal/tests/twice.rs index c40326096..e2a450087 100644 --- a/tokio-signal/tests/twice.rs +++ b/tokio-signal/tests/twice.rs @@ -1,9 +1,10 @@ #![cfg(unix)] - -extern crate libc; +#![deny(warnings, rust_2018_idioms)] pub mod support; -use support::*; +use crate::support::*; + +use libc; #[test] fn twice() { diff --git a/tokio-sync/Cargo.toml b/tokio-sync/Cargo.toml index 072694f29..7217b8a1d 100644 --- a/tokio-sync/Cargo.toml +++ b/tokio-sync/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-sync" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.1.x" git tag. -version = "0.1.5" +# - Create "v0.2.x" git tag. +version = "0.2.0" +edition = "2018" authors = ["Carl Lerche "] license = "MIT" repository = "https://github.com/tokio-rs/tokio" @@ -18,6 +19,7 @@ description = """ Synchronization utilities. """ categories = ["asynchronous"] +publish = false [dependencies] fnv = "1.0.6" @@ -25,6 +27,6 @@ futures = "0.1.19" [dev-dependencies] env_logger = { version = "0.5", default-features = false } -tokio = { version = "0.1.15", path = "../tokio" } +tokio = { version = "0.2.0", path = "../tokio" } tokio-mock-task = "0.1.1" loom = { version = "0.1.1", features = ["futures"] } diff --git a/tokio-sync/benches/mpsc.rs b/tokio-sync/benches/mpsc.rs index 6bb0aac18..4751b3c0b 100644 --- a/tokio-sync/benches/mpsc.rs +++ b/tokio-sync/benches/mpsc.rs @@ -1,9 +1,7 @@ #![feature(test)] -#![cfg_attr(test, deny(warnings))] +#![deny(warnings, rust_2018_idioms)] -extern crate futures; extern crate test; -extern crate tokio_sync; type Medium = [usize; 64]; type Large = [Medium; 64]; diff --git a/tokio-sync/benches/oneshot.rs b/tokio-sync/benches/oneshot.rs index b3170ce42..c2f0ef4bb 100644 --- a/tokio-sync/benches/oneshot.rs +++ b/tokio-sync/benches/oneshot.rs @@ -1,9 +1,7 @@ #![feature(test)] -#![cfg_attr(test, deny(warnings))] +#![deny(warnings, rust_2018_idioms)] -extern crate futures; extern crate test; -extern crate tokio_sync; mod tokio { use futures::{future, Async, Future}; diff --git a/tokio-sync/src/lib.rs b/tokio-sync/src/lib.rs index 6439acdd2..1131899c0 100644 --- a/tokio-sync/src/lib.rs +++ b/tokio-sync/src/lib.rs @@ -1,15 +1,17 @@ #![doc(html_root_url = "https://docs.rs/tokio-sync/0.1.5")] -#![deny(missing_debug_implementations, missing_docs, unreachable_pub)] +#![deny( + missing_debug_implementations, + missing_docs, + unreachable_pub, + rust_2018_idioms +)] #![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! Asynchronous synchronization primitives. //! //! This crate provides primitives for synchronizing asynchronous tasks. -extern crate fnv; -#[macro_use] -extern crate futures; - macro_rules! debug { ($($t:tt)*) => { if false { diff --git a/tokio-sync/src/lock.rs b/tokio-sync/src/lock.rs index b6153800f..017af197c 100644 --- a/tokio-sync/src/lock.rs +++ b/tokio-sync/src/lock.rs @@ -8,11 +8,9 @@ //! This allows you to do something along the lines of: //! //! ```rust,no_run -//! # #[macro_use] -//! # extern crate futures; -//! # extern crate tokio; -//! # use futures::{future, Poll, Async, Future, Stream}; +//! use futures::{try_ready, future, Poll, Async, Future, Stream}; //! use tokio::sync::lock::{Lock, LockGuard}; +//! //! struct MyType { //! lock: Lock, //! } @@ -37,14 +35,13 @@ //! } //! } //! } -//! # fn main() {} //! ``` //! -//! [`Lock`]: struct.Lock.html -//! [`LockGuard`]: struct.LockGuard.html +//! [`Lock`]: struct.Lock.html +//! [`LockGuard`]: struct.LockGuard.html +use crate::semaphore; use futures::Async; -use semaphore; use std::cell::UnsafeCell; use std::fmt; use std::ops::{Deref, DerefMut}; @@ -176,7 +173,7 @@ impl DerefMut for LockGuard { } impl fmt::Display for LockGuard { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&**self, f) } } diff --git a/tokio-sync/src/loom.rs b/tokio-sync/src/loom.rs index a4ec82b17..c46a5f544 100644 --- a/tokio-sync/src/loom.rs +++ b/tokio-sync/src/loom.rs @@ -1,6 +1,6 @@ pub(crate) mod futures { + pub(crate) use crate::task::AtomicTask; pub(crate) use futures::task; - pub(crate) use task::AtomicTask; } pub(crate) mod sync { diff --git a/tokio-sync/src/mpsc/block.rs b/tokio-sync/src/mpsc/block.rs index b59ca5f2a..dfb10a67c 100644 --- a/tokio-sync/src/mpsc/block.rs +++ b/tokio-sync/src/mpsc/block.rs @@ -1,9 +1,8 @@ -use loom::{ +use crate::loom::{ self, sync::atomic::{AtomicPtr, AtomicUsize}, sync::CausalCell, }; - use std::mem::{self, ManuallyDrop}; use std::ops; use std::ptr::{self, NonNull}; diff --git a/tokio-sync/src/mpsc/bounded.rs b/tokio-sync/src/mpsc/bounded.rs index de65dd55c..b2fce168b 100644 --- a/tokio-sync/src/mpsc/bounded.rs +++ b/tokio-sync/src/mpsc/bounded.rs @@ -1,7 +1,5 @@ use super::chan; - use futures::{Poll, Sink, StartSend, Stream}; - use std::fmt; /// Send values to the associated `Receiver`. @@ -20,7 +18,7 @@ impl Clone for Sender { } impl fmt::Debug for Sender { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Sender") .field("chan", &self.chan) .finish() @@ -36,7 +34,7 @@ pub struct Receiver { } impl fmt::Debug for Receiver { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Receiver") .field("chan", &self.chan) .finish() @@ -80,9 +78,6 @@ pub struct RecvError(()); /// # Examples /// /// ```rust -/// extern crate futures; -/// extern crate tokio; -/// /// use tokio::sync::mpsc::channel; /// use tokio::prelude::*; /// use futures::future::lazy; @@ -114,7 +109,7 @@ pub struct RecvError(()); /// ``` pub fn channel(buffer: usize) -> (Sender, Receiver) { assert!(buffer > 0, "mpsc bounded channel requires buffer > 0"); - let semaphore = (::semaphore::Semaphore::new(buffer), buffer); + let semaphore = (crate::semaphore::Semaphore::new(buffer), buffer); let (tx, rx) = chan::channel(semaphore); let tx = Sender::new(tx); @@ -125,7 +120,7 @@ pub fn channel(buffer: usize) -> (Sender, Receiver) { /// Channel semaphore is a tuple of the semaphore implementation and a `usize` /// representing the channel bound. -type Semaphore = (::semaphore::Semaphore, usize); +type Semaphore = (crate::semaphore::Semaphore, usize); impl Receiver { pub(crate) fn new(chan: chan::Rx) -> Receiver { @@ -218,7 +213,7 @@ impl Sink for Sender { // ===== impl SendError ===== impl fmt::Display for SendError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } @@ -258,7 +253,7 @@ impl TrySendError { } impl fmt::Display for TrySendError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } @@ -288,7 +283,7 @@ impl From<(T, chan::TrySendError)> for TrySendError { // ===== impl RecvError ===== impl fmt::Display for RecvError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } diff --git a/tokio-sync/src/mpsc/chan.rs b/tokio-sync/src/mpsc/chan.rs index 894da468f..fae3159aa 100644 --- a/tokio-sync/src/mpsc/chan.rs +++ b/tokio-sync/src/mpsc/chan.rs @@ -1,12 +1,10 @@ use super::list; -use futures::Poll; - -use loom::{ +use crate::loom::{ futures::AtomicTask, sync::atomic::AtomicUsize, sync::{Arc, CausalCell}, }; - +use futures::Poll; use std::fmt; use std::process; use std::sync::atomic::Ordering::{AcqRel, Relaxed}; @@ -22,7 +20,7 @@ where S::Permit: fmt::Debug, S: fmt::Debug, { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Tx") .field("inner", &self.inner) .field("permit", &self.permit) @@ -39,7 +37,7 @@ impl fmt::Debug for Rx where S: fmt::Debug, { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Rx").field("inner", &self.inner).finish() } } @@ -99,7 +97,7 @@ impl fmt::Debug for Chan where S: fmt::Debug, { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Chan") .field("tx", &self.tx) .field("semaphore", &self.semaphore) @@ -120,7 +118,7 @@ struct RxFields { } impl fmt::Debug for RxFields { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("RxFields") .field("list", &self.list) .field("rx_closed", &self.rx_closed) @@ -337,7 +335,7 @@ impl Drop for Chan { } } -use semaphore::TryAcquireError; +use crate::semaphore::TryAcquireError; impl From for TrySendError { fn from(src: TryAcquireError) -> TrySendError { @@ -353,9 +351,9 @@ impl From for TrySendError { // ===== impl Semaphore for (::Semaphore, capacity) ===== -use semaphore::Permit; +use crate::semaphore::Permit; -impl Semaphore for (::semaphore::Semaphore, usize) { +impl Semaphore for (crate::semaphore::Semaphore, usize) { type Permit = Permit; fn new_permit() -> Permit { diff --git a/tokio-sync/src/mpsc/list.rs b/tokio-sync/src/mpsc/list.rs index 782ab12a8..595af88fc 100644 --- a/tokio-sync/src/mpsc/list.rs +++ b/tokio-sync/src/mpsc/list.rs @@ -1,12 +1,10 @@ //! A concurrent, lock-free, FIFO list. use super::block::{self, Block}; - -use loom::{ +use crate::loom::{ self, sync::atomic::{AtomicPtr, AtomicUsize}, }; - use std::fmt; use std::ptr::NonNull; use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release}; @@ -214,7 +212,7 @@ impl Tx { } impl fmt::Debug for Tx { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Tx") .field("block_tail", &self.block_tail.load(Relaxed)) .field("tail_position", &self.tail_position.load(Relaxed)) @@ -339,7 +337,7 @@ impl Rx { } impl fmt::Debug for Rx { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Rx") .field("head", &self.head) .field("index", &self.index) diff --git a/tokio-sync/src/mpsc/mod.rs b/tokio-sync/src/mpsc/mod.rs index 382e9bc68..320980c75 100644 --- a/tokio-sync/src/mpsc/mod.rs +++ b/tokio-sync/src/mpsc/mod.rs @@ -41,14 +41,12 @@ mod list; mod unbounded; pub use self::bounded::{channel, Receiver, Sender}; - pub use self::unbounded::{unbounded_channel, UnboundedReceiver, UnboundedSender}; pub mod error { //! Channel error types pub use super::bounded::{RecvError, SendError, TrySendError}; - pub use super::unbounded::{UnboundedRecvError, UnboundedSendError, UnboundedTrySendError}; } diff --git a/tokio-sync/src/mpsc/unbounded.rs b/tokio-sync/src/mpsc/unbounded.rs index 3caa4b5d5..58967c915 100644 --- a/tokio-sync/src/mpsc/unbounded.rs +++ b/tokio-sync/src/mpsc/unbounded.rs @@ -1,8 +1,6 @@ use super::chan; - +use crate::loom::sync::atomic::AtomicUsize; use futures::{Poll, Sink, StartSend, Stream}; -use loom::sync::atomic::AtomicUsize; - use std::fmt; /// Send values to the associated `UnboundedReceiver`. @@ -22,7 +20,7 @@ impl Clone for UnboundedSender { } impl fmt::Debug for UnboundedSender { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("UnboundedSender") .field("chan", &self.chan) .finish() @@ -39,7 +37,7 @@ pub struct UnboundedReceiver { } impl fmt::Debug for UnboundedReceiver { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("UnboundedReceiver") .field("chan", &self.chan) .finish() @@ -140,7 +138,7 @@ impl Sink for UnboundedSender { // ===== impl UnboundedSendError ===== impl fmt::Display for UnboundedSendError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } @@ -162,7 +160,7 @@ impl UnboundedTrySendError { } impl fmt::Display for UnboundedTrySendError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } @@ -184,7 +182,7 @@ impl From<(T, chan::TrySendError)> for UnboundedTrySendError { // ===== impl UnboundedRecvError ===== impl fmt::Display for UnboundedRecvError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } diff --git a/tokio-sync/src/oneshot.rs b/tokio-sync/src/oneshot.rs index bb11d4e6f..d3531bd97 100644 --- a/tokio-sync/src/oneshot.rs +++ b/tokio-sync/src/oneshot.rs @@ -1,13 +1,11 @@ //! A channel for sending a single message between asynchronous tasks. -use loom::{ +use crate::loom::{ futures::task::{self, Task}, sync::atomic::AtomicUsize, sync::CausalCell, }; - use futures::{Async, Future, Poll}; - use std::fmt; use std::mem::{self, ManuallyDrop}; use std::sync::atomic::Ordering::{self, AcqRel, Acquire}; @@ -45,7 +43,7 @@ pub mod error { // ===== impl RecvError ===== impl fmt::Display for RecvError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } @@ -60,7 +58,7 @@ pub mod error { // ===== impl TryRecvError ===== impl fmt::Display for TryRecvError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } @@ -105,9 +103,6 @@ struct State(usize); /// # Examples /// /// ``` -/// extern crate futures; -/// extern crate tokio; -/// /// use tokio::sync::oneshot; /// use futures::Future; /// use std::thread; @@ -451,7 +446,7 @@ impl Drop for Inner { } impl fmt::Debug for Inner { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use std::sync::atomic::Ordering::Relaxed; fmt.debug_struct("Inner") @@ -532,7 +527,7 @@ impl State { } impl fmt::Debug for State { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("State") .field("is_complete", &self.is_complete()) .field("is_closed", &self.is_closed()) diff --git a/tokio-sync/src/semaphore.rs b/tokio-sync/src/semaphore.rs index 865264f8b..43e89c371 100644 --- a/tokio-sync/src/semaphore.rs +++ b/tokio-sync/src/semaphore.rs @@ -8,7 +8,7 @@ //! section. If no permits are available, then acquiring the semaphore returns //! `NotReady`. The task is notified once a permit becomes available. -use loom::{ +use crate::loom::{ futures::AtomicTask, sync::{ atomic::{AtomicPtr, AtomicUsize}, @@ -16,9 +16,7 @@ use loom::{ }, yield_now, }; - use futures::Poll; - use std::fmt; use std::ptr::{self, NonNull}; use std::sync::atomic::Ordering::{self, AcqRel, Acquire, Relaxed, Release}; @@ -531,7 +529,7 @@ impl Semaphore { } impl fmt::Debug for Semaphore { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Semaphore") .field("state", &SemState::load(&self.state, Relaxed)) .field("head", &self.head.with(|ptr| ptr)) @@ -683,7 +681,7 @@ fn to_try_acquire(_: AcquireError) -> TryAcquireError { } impl fmt::Display for AcquireError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } @@ -729,7 +727,7 @@ impl TryAcquireError { } impl fmt::Display for TryAcquireError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } @@ -1073,7 +1071,7 @@ impl SemState { } impl fmt::Debug for SemState { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut fmt = fmt.debug_struct("SemState"); if self.is_waiter() { diff --git a/tokio-sync/src/task/atomic_task.rs b/tokio-sync/src/task/atomic_task.rs index 2161e0e1c..73110da2a 100644 --- a/tokio-sync/src/task/atomic_task.rs +++ b/tokio-sync/src/task/atomic_task.rs @@ -1,9 +1,8 @@ -use loom::{ +use crate::loom::{ futures::task::{self, Task}, sync::atomic::AtomicUsize, sync::CausalCell, }; - use std::fmt; use std::sync::atomic::Ordering::{AcqRel, Acquire, Release}; @@ -290,7 +289,7 @@ impl Default for AtomicTask { } impl fmt::Debug for AtomicTask { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "AtomicTask") } } diff --git a/tokio-sync/src/watch.rs b/tokio-sync/src/watch.rs index b3303bdce..aab016b50 100644 --- a/tokio-sync/src/watch.rs +++ b/tokio-sync/src/watch.rs @@ -18,9 +18,6 @@ //! # Examples //! //! ``` -//! # extern crate futures; -//! extern crate tokio; -//! //! use tokio::prelude::*; //! use tokio::sync::watch; //! @@ -58,8 +55,7 @@ use fnv::FnvHashMap; use futures::task::AtomicTask; -use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; - +use futures::{try_ready, Async, AsyncSink, Poll, Sink, StartSend, Stream}; use std::ops; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; @@ -97,7 +93,7 @@ pub struct Sender { /// long lived borrows could cause the produce half to block. It is recommended /// to keep the borrow as short lived as possible. #[derive(Debug)] -pub struct Ref<'a, T: 'a> { +pub struct Ref<'a, T> { inner: RwLockReadGuard<'a, T>, } @@ -121,7 +117,7 @@ pub mod error { // ===== impl RecvError ===== impl fmt::Display for RecvError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } @@ -136,7 +132,7 @@ pub mod error { // ===== impl SendError ===== impl fmt::Display for SendError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } @@ -189,9 +185,6 @@ const CLOSED: usize = 1; /// # Examples /// /// ``` -/// # extern crate futures; -/// extern crate tokio; -/// /// use tokio::prelude::*; /// use tokio::sync::watch; /// @@ -250,12 +243,12 @@ impl Receiver { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # use tokio::sync::watch; + /// use tokio::sync::watch; + /// /// let (_, rx) = watch::channel("hello"); /// assert_eq!(*rx.get_ref(), "hello"); /// ``` - pub fn get_ref(&self) -> Ref { + pub fn get_ref(&self) -> Ref<'_, T> { let inner = self.shared.value.read().unwrap(); Ref { inner } } @@ -268,7 +261,7 @@ impl Receiver { /// /// Only the **most recent** value is returned. If the receiver is falling /// behind the sender, intermediate values are dropped. - pub fn poll_ref(&mut self) -> Poll>, error::RecvError> { + pub fn poll_ref(&mut self) -> Poll>, error::RecvError> { // Make sure the task is up to date self.inner.task.register(); diff --git a/tokio-sync/tests/atomic_task.rs b/tokio-sync/tests/atomic_task.rs index cfe91e1af..8e77d624f 100644 --- a/tokio-sync/tests/atomic_task.rs +++ b/tokio-sync/tests/atomic_task.rs @@ -1,8 +1,4 @@ -#![deny(warnings)] - -extern crate futures; -extern crate tokio_mock_task; -extern crate tokio_sync; +#![deny(warnings, rust_2018_idioms)] use futures::task::{self, Task}; use tokio_mock_task::*; diff --git a/tokio-sync/tests/errors.rs b/tokio-sync/tests/errors.rs index 129cbfc2c..97ab7e578 100644 --- a/tokio-sync/tests/errors.rs +++ b/tokio-sync/tests/errors.rs @@ -1,6 +1,4 @@ -#![deny(warnings)] - -extern crate tokio_sync; +#![deny(warnings, rust_2018_idioms)] fn is_error() {} diff --git a/tokio-sync/tests/fuzz_atomic_task.rs b/tokio-sync/tests/fuzz_atomic_task.rs index 4381a7efb..12d3fb74b 100644 --- a/tokio-sync/tests/fuzz_atomic_task.rs +++ b/tokio-sync/tests/fuzz_atomic_task.rs @@ -1,6 +1,5 @@ -#![deny(warnings)] +#![deny(warnings, rust_2018_idioms)] -extern crate futures; #[macro_use] extern crate loom; @@ -8,15 +7,12 @@ extern crate loom; #[path = "../src/task/atomic_task.rs"] mod atomic_task; -use atomic_task::AtomicTask; - +use crate::atomic_task::AtomicTask; +use futures::future::poll_fn; +use futures::Async; use loom::futures::block_on; use loom::sync::atomic::AtomicUsize; use loom::thread; - -use futures::future::poll_fn; -use futures::Async; - use std::sync::atomic::Ordering::Relaxed; use std::sync::Arc; diff --git a/tokio-sync/tests/fuzz_list.rs b/tokio-sync/tests/fuzz_list.rs index 43799020e..4edd21d7f 100644 --- a/tokio-sync/tests/fuzz_list.rs +++ b/tokio-sync/tests/fuzz_list.rs @@ -1,6 +1,5 @@ -#![deny(warnings)] +#![deny(warnings, rust_2018_idioms)] -extern crate futures; #[macro_use] extern crate loom; @@ -21,12 +20,11 @@ mod block; const BLOCK_CAP: usize = 2; use loom::thread; - use std::sync::Arc; #[test] fn smoke() { - use block::Read::*; + use crate::block::Read::*; const NUM_TX: usize = 2; const NUM_MSG: usize = 2; diff --git a/tokio-sync/tests/fuzz_mpsc.rs b/tokio-sync/tests/fuzz_mpsc.rs index da83100f2..2a7b75528 100644 --- a/tokio-sync/tests/fuzz_mpsc.rs +++ b/tokio-sync/tests/fuzz_mpsc.rs @@ -1,4 +1,5 @@ -extern crate futures; +#![deny(warnings, rust_2018_idioms)] + #[macro_use] extern crate loom; diff --git a/tokio-sync/tests/fuzz_oneshot.rs b/tokio-sync/tests/fuzz_oneshot.rs index bf9d2836f..d1e4eeed9 100644 --- a/tokio-sync/tests/fuzz_oneshot.rs +++ b/tokio-sync/tests/fuzz_oneshot.rs @@ -1,13 +1,11 @@ -#![deny(warnings)] - -extern crate futures; -extern crate loom; +#![deny(warnings, rust_2018_idioms)] #[path = "../src/oneshot.rs"] #[allow(warnings)] mod oneshot; -use futures::{Async, Future}; +use futures::{self, Async, Future}; +use loom; use loom::futures::block_on; use loom::thread; diff --git a/tokio-sync/tests/fuzz_semaphore.rs b/tokio-sync/tests/fuzz_semaphore.rs index e88775af1..58c67dc39 100644 --- a/tokio-sync/tests/fuzz_semaphore.rs +++ b/tokio-sync/tests/fuzz_semaphore.rs @@ -1,7 +1,5 @@ -#![deny(warnings)] +#![deny(warnings, rust_2018_idioms)] -#[macro_use] -extern crate futures; #[macro_use] extern crate loom; @@ -9,12 +7,10 @@ extern crate loom; #[allow(warnings)] mod semaphore; -use semaphore::*; - -use futures::{future, Async, Future, Poll}; +use crate::semaphore::*; +use futures::{future, try_ready, Async, Future, Poll}; use loom::futures::block_on; use loom::thread; - use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use std::sync::Arc; diff --git a/tokio-sync/tests/lock.rs b/tokio-sync/tests/lock.rs index 3366d2be5..0e74efa0b 100644 --- a/tokio-sync/tests/lock.rs +++ b/tokio-sync/tests/lock.rs @@ -1,9 +1,6 @@ -#![deny(warnings)] - -extern crate futures; -extern crate tokio_mock_task; -extern crate tokio_sync; +#![deny(warnings, rust_2018_idioms)] +use futures; use tokio_mock_task::*; use tokio_sync::lock::Lock; diff --git a/tokio-sync/tests/mpsc.rs b/tokio-sync/tests/mpsc.rs index 3572b94b9..af2d1dd7a 100644 --- a/tokio-sync/tests/mpsc.rs +++ b/tokio-sync/tests/mpsc.rs @@ -1,16 +1,11 @@ -#![deny(warnings)] - -extern crate futures; -extern crate tokio_mock_task; -extern crate tokio_sync; - -use tokio_mock_task::*; -use tokio_sync::mpsc; +#![deny(warnings, rust_2018_idioms)] +use futures; use futures::prelude::*; - use std::sync::Arc; use std::thread; +use tokio_mock_task::*; +use tokio_sync::mpsc; trait AssertSend: Send {} impl AssertSend for mpsc::Sender {} diff --git a/tokio-sync/tests/oneshot.rs b/tokio-sync/tests/oneshot.rs index 46c67a74c..cc14dc958 100644 --- a/tokio-sync/tests/oneshot.rs +++ b/tokio-sync/tests/oneshot.rs @@ -1,14 +1,10 @@ -#![deny(warnings)] - -extern crate futures; -extern crate tokio_mock_task; -extern crate tokio_sync; +#![deny(warnings, rust_2018_idioms)] +use futures; +use futures::prelude::*; use tokio_mock_task::*; use tokio_sync::oneshot; -use futures::prelude::*; - macro_rules! assert_ready { ($e:expr) => {{ match $e { diff --git a/tokio-sync/tests/semaphore.rs b/tokio-sync/tests/semaphore.rs index 8cd3533fa..c775bf1a0 100644 --- a/tokio-sync/tests/semaphore.rs +++ b/tokio-sync/tests/semaphore.rs @@ -1,9 +1,6 @@ -#![deny(warnings)] - -extern crate futures; -extern crate tokio_mock_task; -extern crate tokio_sync; +#![deny(warnings, rust_2018_idioms)] +use futures; use tokio_mock_task::*; use tokio_sync::semaphore::{Permit, Semaphore}; diff --git a/tokio-sync/tests/watch.rs b/tokio-sync/tests/watch.rs index 7e4e35b56..8424a181d 100644 --- a/tokio-sync/tests/watch.rs +++ b/tokio-sync/tests/watch.rs @@ -1,7 +1,6 @@ -extern crate futures; -extern crate tokio_mock_task; -extern crate tokio_sync; +#![deny(warnings, rust_2018_idioms)] +use futures; use tokio_mock_task::*; use tokio_sync::watch; diff --git a/tokio-tcp/Cargo.toml b/tokio-tcp/Cargo.toml index 8a27250f7..5e87b9b9d 100644 --- a/tokio-tcp/Cargo.toml +++ b/tokio-tcp/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-tcp" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.1.x" git tag. -version = "0.1.3" +# - Create "v0.2.x" git tag. +version = "0.2.0" +edition = "2018" authors = ["Carl Lerche "] license = "MIT" repository = "https://github.com/tokio-rs/tokio" @@ -18,10 +19,11 @@ description = """ TCP bindings for tokio. """ categories = ["asynchronous"] +publish = false [dependencies] -tokio-io = "0.1.6" -tokio-reactor = "0.1.1" +tokio-io = { version = "0.2.0", path = "../tokio-io" } +tokio-reactor = { version = "0.2.0", path = "../tokio-reactor" } bytes = "0.4" mio = "0.6.14" iovec = "0.1" @@ -29,4 +31,4 @@ futures = "0.1.19" [dev-dependencies] env_logger = { version = "0.5", default-features = false } -tokio = "0.1.13" +tokio = { version = "0.2.0", path = "../tokio" } diff --git a/tokio-tcp/src/incoming.rs b/tokio-tcp/src/incoming.rs index 3c6968791..dd1414c85 100644 --- a/tokio-tcp/src/incoming.rs +++ b/tokio-tcp/src/incoming.rs @@ -1,8 +1,7 @@ use super::TcpListener; use super::TcpStream; - use futures::stream::Stream; -use futures::{Async, Poll}; +use futures::{try_ready, Async, Poll}; use std::io; /// Stream returned by the `TcpListener::incoming` function representing the diff --git a/tokio-tcp/src/lib.rs b/tokio-tcp/src/lib.rs index c8aa4102f..979d6d295 100644 --- a/tokio-tcp/src/lib.rs +++ b/tokio-tcp/src/lib.rs @@ -1,5 +1,7 @@ #![doc(html_root_url = "https://docs.rs/tokio-tcp/0.1.3")] -#![deny(missing_docs, warnings, missing_debug_implementations)] +#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! TCP bindings for `tokio`. //! @@ -22,14 +24,6 @@ //! [incoming_method]: struct.TcpListener.html#method.incoming //! [`Incoming`]: struct.Incoming.html -extern crate bytes; -#[macro_use] -extern crate futures; -extern crate iovec; -extern crate mio; -extern crate tokio_io; -extern crate tokio_reactor; - mod incoming; mod listener; mod stream; diff --git a/tokio-tcp/src/listener.rs b/tokio-tcp/src/listener.rs index e60b02ae7..0da00dc9a 100644 --- a/tokio-tcp/src/listener.rs +++ b/tokio-tcp/src/listener.rs @@ -1,12 +1,10 @@ use super::Incoming; use super::TcpStream; - +use futures::{try_ready, Async, Poll}; +use mio; use std::fmt; use std::io; use std::net::{self, SocketAddr}; - -use futures::{Async, Poll}; -use mio; use tokio_reactor::{Handle, PollEvented}; /// An I/O object representing a TCP socket listening for incoming connections. @@ -17,9 +15,6 @@ use tokio_reactor::{Handle, PollEvented}; /// # Examples /// /// ```no_run -/// extern crate tokio; -/// extern crate futures; -/// /// use futures::stream::Stream; /// use std::net::SocketAddr; /// use tokio::net::{TcpListener, TcpStream}; @@ -28,20 +23,18 @@ use tokio_reactor::{Handle, PollEvented}; /// // ... /// } /// -/// fn main() -> Result<(), Box> { -/// let addr = "127.0.0.1:8080".parse::()?; -/// let listener = TcpListener::bind(&addr)?; +/// let addr = "127.0.0.1:8080".parse::()?; +/// let listener = TcpListener::bind(&addr)?; /// -/// // accept connections and process them -/// tokio::run(listener.incoming() -/// .map_err(|e| eprintln!("failed to accept socket; error = {:?}", e)) -/// .for_each(|socket| { -/// process_socket(socket); -/// Ok(()) -/// }) -/// ); -/// Ok(()) -/// } +/// // accept connections and process them +/// tokio::run(listener.incoming() +/// .map_err(|e| eprintln!("failed to accept socket; error = {:?}", e)) +/// .for_each(|socket| { +/// process_socket(socket); +/// Ok(()) +/// }) +/// ); +/// # Ok::<_, Box>(()) /// ``` pub struct TcpListener { io: PollEvented, @@ -56,15 +49,12 @@ impl TcpListener { /// # Examples /// /// ``` - /// # extern crate tokio; /// use std::net::SocketAddr; /// use tokio::net::TcpListener; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:0".parse::()?; /// let listener = TcpListener::bind(&addr)?; - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn bind(addr: &SocketAddr) -> io::Result { let l = mio::net::TcpListener::bind(addr)?; @@ -102,13 +92,10 @@ impl TcpListener { /// # Examples /// /// ```no_run - /// # extern crate tokio; - /// # extern crate futures; /// use std::net::SocketAddr; /// use tokio::net::TcpListener; /// use futures::Async; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:0".parse::()?; /// let mut listener = TcpListener::bind(&addr)?; /// match listener.poll_accept() { @@ -116,8 +103,7 @@ impl TcpListener { /// Ok(Async::NotReady) => println!("listener not ready to accept!"), /// Err(e) => eprintln!("got an error: {}", e), /// } - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn poll_accept(&mut self) -> Poll<(TcpStream, SocketAddr), io::Error> { let (io, addr) = try_ready!(self.poll_accept_std()); @@ -160,13 +146,10 @@ impl TcpListener { /// # Examples /// /// ```no_run - /// # extern crate tokio; - /// # extern crate futures; /// use std::net::SocketAddr; /// use tokio::net::TcpListener; /// use futures::Async; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:0".parse::()?; /// let mut listener = TcpListener::bind(&addr)?; /// match listener.poll_accept_std() { @@ -174,8 +157,7 @@ impl TcpListener { /// Ok(Async::NotReady) => println!("listener not ready to accept!"), /// Err(e) => eprintln!("got an error: {}", e), /// } - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn poll_accept_std(&mut self) -> Poll<(net::TcpStream, SocketAddr), io::Error> { try_ready!(self.io.poll_read_ready(mio::Ready::readable())); @@ -223,17 +205,13 @@ impl TcpListener { /// # Examples /// /// ```no_run - /// # extern crate tokio; - /// # extern crate tokio_reactor; /// use tokio::net::TcpListener; /// use std::net::TcpListener as StdTcpListener; /// use tokio::reactor::Handle; /// - /// # fn main() -> Result<(), Box> { /// let std_listener = StdTcpListener::bind("127.0.0.1:0")?; /// let listener = TcpListener::from_std(std_listener, &Handle::default())?; - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn from_std(listener: net::TcpListener, handle: &Handle) -> io::Result { let io = mio::net::TcpListener::from_std(listener)?; @@ -254,17 +232,14 @@ impl TcpListener { /// # Examples /// /// ``` - /// # extern crate tokio; /// use tokio::net::TcpListener; /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let listener = TcpListener::bind(&addr)?; /// assert_eq!(listener.local_addr()?, /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080))); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn local_addr(&self) -> io::Result { self.io.get_ref().local_addr() @@ -289,13 +264,10 @@ impl TcpListener { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpListener; /// use futures::stream::Stream; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:0".parse::()?; /// let listener = TcpListener::bind(&addr)?; /// @@ -305,8 +277,7 @@ impl TcpListener { /// println!("new socket!"); /// Ok(()) /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn incoming(self) -> Incoming { Incoming::new(self) @@ -321,17 +292,16 @@ impl TcpListener { /// # Examples /// /// ``` - /// # extern crate tokio; /// use tokio::net::TcpListener; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:0".parse::()?; /// let listener = TcpListener::bind(&addr)?; + /// /// listener.set_ttl(100).expect("could not set TTL"); + /// /// assert_eq!(listener.ttl()?, 100); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn ttl(&self) -> io::Result { self.io.get_ref().ttl() @@ -345,16 +315,14 @@ impl TcpListener { /// # Examples /// /// ``` - /// # extern crate tokio; /// use tokio::net::TcpListener; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:0".parse::()?; /// let listener = TcpListener::bind(&addr)?; + /// /// listener.set_ttl(100).expect("could not set TTL"); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { self.io.get_ref().set_ttl(ttl) @@ -362,7 +330,7 @@ impl TcpListener { } impl fmt::Debug for TcpListener { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.io.get_ref().fmt(f) } } diff --git a/tokio-tcp/src/stream.rs b/tokio-tcp/src/stream.rs index 98f15aeba..1a00679de 100644 --- a/tokio-tcp/src/stream.rs +++ b/tokio-tcp/src/stream.rs @@ -1,13 +1,12 @@ +use bytes::{Buf, BufMut}; +use futures::{try_ready, Async, Future, Poll}; +use iovec::IoVec; +use mio; use std::fmt; use std::io::{self, Read, Write}; use std::mem; use std::net::{self, Shutdown, SocketAddr}; use std::time::Duration; - -use bytes::{Buf, BufMut}; -use futures::{Async, Future, Poll}; -use iovec::IoVec; -use mio; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_reactor::{Handle, PollEvented}; @@ -23,22 +22,18 @@ use tokio_reactor::{Handle, PollEvented}; /// # Examples /// /// ``` -/// # extern crate tokio; -/// # extern crate futures; /// use futures::Future; /// use tokio::io::AsyncWrite; /// use tokio::net::TcpStream; /// use std::net::SocketAddr; /// -/// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:34254".parse::()?; /// let stream = TcpStream::connect(&addr); /// stream.map(|mut stream| { /// // Attempt to write bytes asynchronously to the stream /// stream.poll_write(&[1]); /// }); -/// # Ok(()) -/// # } +/// # Ok::<_, Box>(()) /// ``` pub struct TcpStream { io: PollEvented, @@ -71,19 +66,15 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use futures::Future; /// use tokio::net::TcpStream; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:34254".parse::()?; /// let stream = TcpStream::connect(&addr) /// .map(|stream| /// println!("successfully connected to {}", stream.local_addr().unwrap())); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn connect(addr: &SocketAddr) -> ConnectFuture { use self::ConnectFutureState::*; @@ -110,17 +101,13 @@ impl TcpStream { /// # Examples /// /// ```no_run - /// # extern crate tokio; - /// # extern crate tokio_reactor; /// use tokio::net::TcpStream; /// use std::net::TcpStream as StdTcpStream; /// use tokio_reactor::Handle; /// - /// # fn main() -> Result<(), Box> { /// let std_stream = StdTcpStream::connect("127.0.0.1:34254")?; /// let stream = TcpStream::from_std(std_stream, &Handle::default())?; - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn from_std(stream: net::TcpStream, handle: &Handle) -> io::Result { let io = mio::net::TcpStream::from_stream(stream)?; @@ -188,18 +175,15 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate mio; - /// # extern crate tokio; - /// # extern crate futures; /// use mio::Ready; /// use futures::Async; /// use futures::Future; /// use tokio::net::TcpStream; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:34254".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// match stream.poll_read_ready(Ready::readable()) { /// Ok(Async::Ready(_)) => println!("read ready"), @@ -207,8 +191,7 @@ impl TcpStream { /// Err(e) => eprintln!("got error: {}", e), /// } /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn poll_read_ready(&self, mask: mio::Ready) -> Poll { self.io.poll_read_ready(mask) @@ -232,16 +215,14 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use futures::Async; /// use futures::Future; /// use tokio::net::TcpStream; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:34254".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// match stream.poll_write_ready() { /// Ok(Async::Ready(_)) => println!("write ready"), @@ -249,8 +230,7 @@ impl TcpStream { /// Err(e) => eprintln!("got error: {}", e), /// } /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn poll_write_ready(&self) -> Poll { self.io.poll_write_ready() @@ -261,21 +241,18 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// assert_eq!(stream.local_addr().unwrap(), /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080))); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn local_addr(&self) -> io::Result { self.io.get_ref().local_addr() @@ -285,21 +262,18 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// assert_eq!(stream.peer_addr().unwrap(), /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080))); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn peer_addr(&self) -> io::Result { self.io.get_ref().peer_addr() @@ -336,16 +310,14 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Async; /// use futures::Future; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|mut stream| { /// let mut buf = [0; 10]; /// match stream.poll_peek(&mut buf) { @@ -354,8 +326,7 @@ impl TcpStream { /// Err(e) => eprintln!("got error: {}", e), /// } /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn poll_peek(&mut self, buf: &mut [u8]) -> Poll { try_ready!(self.io.poll_read_ready(mio::Ready::readable())); @@ -379,20 +350,17 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::{Shutdown, SocketAddr}; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// stream.shutdown(Shutdown::Both) /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { self.io.get_ref().shutdown(how) @@ -407,21 +375,18 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// stream.set_nodelay(true).expect("set_nodelay call failed");; /// assert_eq!(stream.nodelay().unwrap_or(false), true); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn nodelay(&self) -> io::Result { self.io.get_ref().nodelay() @@ -438,20 +403,17 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// stream.set_nodelay(true).expect("set_nodelay call failed"); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { self.io.get_ref().set_nodelay(nodelay) @@ -466,21 +428,18 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// stream.set_recv_buffer_size(100).expect("set_recv_buffer_size failed"); /// assert_eq!(stream.recv_buffer_size().unwrap_or(0), 100); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn recv_buffer_size(&self) -> io::Result { self.io.get_ref().recv_buffer_size() @@ -494,20 +453,17 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// stream.set_recv_buffer_size(100).expect("set_recv_buffer_size failed"); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { self.io.get_ref().set_recv_buffer_size(size) @@ -522,21 +478,18 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// stream.set_send_buffer_size(100).expect("set_send_buffer_size failed"); /// assert_eq!(stream.send_buffer_size().unwrap_or(0), 100); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn send_buffer_size(&self) -> io::Result { self.io.get_ref().send_buffer_size() @@ -550,20 +503,17 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// stream.set_send_buffer_size(100).expect("set_send_buffer_size failed"); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { self.io.get_ref().set_send_buffer_size(size) @@ -579,21 +529,18 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// stream.set_keepalive(None).expect("set_keepalive failed"); /// assert_eq!(stream.keepalive().unwrap(), None); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn keepalive(&self) -> io::Result> { self.io.get_ref().keepalive() @@ -615,20 +562,17 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// stream.set_keepalive(None).expect("set_keepalive failed"); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn set_keepalive(&self, keepalive: Option) -> io::Result<()> { self.io.get_ref().set_keepalive(keepalive) @@ -643,21 +587,18 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// stream.set_ttl(100).expect("set_ttl failed"); /// assert_eq!(stream.ttl().unwrap_or(0), 100); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn ttl(&self) -> io::Result { self.io.get_ref().ttl() @@ -671,20 +612,17 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// stream.set_ttl(100).expect("set_ttl failed"); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { self.io.get_ref().set_ttl(ttl) @@ -700,21 +638,18 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// stream.set_linger(None).expect("set_linger failed"); /// assert_eq!(stream.linger().unwrap(), None); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn linger(&self) -> io::Result> { self.io.get_ref().linger() @@ -735,20 +670,17 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// stream.set_linger(None).expect("set_linger failed"); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` pub fn set_linger(&self, dur: Option) -> io::Result<()> { self.io.get_ref().set_linger(dur) @@ -764,20 +696,17 @@ impl TcpStream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::net::TcpStream; /// use futures::Future; /// use std::net::SocketAddr; /// - /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:8080".parse::()?; /// let stream = TcpStream::connect(&addr); + /// /// stream.map(|stream| { /// let clone = stream.try_clone().unwrap(); /// }); - /// # Ok(()) - /// # } + /// # Ok::<_, Box>(()) /// ``` #[deprecated(since = "0.1.14", note = "use `split()` instead")] #[doc(hidden)] @@ -948,7 +877,7 @@ impl<'a> AsyncWrite for &'a TcpStream { } impl fmt::Debug for TcpStream { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.io.get_ref().fmt(f) } } diff --git a/tokio-tcp/tests/chain.rs b/tokio-tcp/tests/chain.rs index e76edff8d..a8531058a 100644 --- a/tokio-tcp/tests/chain.rs +++ b/tokio-tcp/tests/chain.rs @@ -1,13 +1,10 @@ -extern crate futures; -extern crate tokio_io; -extern crate tokio_tcp; - -use std::io::{Read, Write}; -use std::net::TcpStream; -use std::thread; +#![deny(warnings, rust_2018_idioms)] use futures::stream::Stream; use futures::Future; +use std::io::{Read, Write}; +use std::net::TcpStream; +use std::thread; use tokio_io::io::read_to_end; use tokio_tcp::TcpListener; diff --git a/tokio-tcp/tests/echo.rs b/tokio-tcp/tests/echo.rs index 62c1f135e..42a00d2bf 100644 --- a/tokio-tcp/tests/echo.rs +++ b/tokio-tcp/tests/echo.rs @@ -1,14 +1,11 @@ -extern crate env_logger; -extern crate futures; -extern crate tokio_io; -extern crate tokio_tcp; +#![deny(warnings, rust_2018_idioms)] +use env_logger; +use futures::stream::Stream; +use futures::Future; use std::io::{Read, Write}; use std::net::TcpStream; use std::thread; - -use futures::stream::Stream; -use futures::Future; use tokio_io::io::copy; use tokio_io::AsyncRead; use tokio_tcp::TcpListener; diff --git a/tokio-tcp/tests/limit.rs b/tokio-tcp/tests/limit.rs index 23ec252da..63ac8fd03 100644 --- a/tokio-tcp/tests/limit.rs +++ b/tokio-tcp/tests/limit.rs @@ -1,13 +1,10 @@ -extern crate futures; -extern crate tokio_io; -extern crate tokio_tcp; - -use std::io::{Read, Write}; -use std::net::TcpStream; -use std::thread; +#![deny(warnings, rust_2018_idioms)] use futures::stream::Stream; use futures::Future; +use std::io::{Read, Write}; +use std::net::TcpStream; +use std::thread; use tokio_io::io::read_to_end; use tokio_tcp::TcpListener; diff --git a/tokio-tcp/tests/stream-buffered.rs b/tokio-tcp/tests/stream-buffered.rs index 03e512ad6..df2fe98fa 100644 --- a/tokio-tcp/tests/stream-buffered.rs +++ b/tokio-tcp/tests/stream-buffered.rs @@ -1,14 +1,11 @@ -extern crate env_logger; -extern crate futures; -extern crate tokio_io; -extern crate tokio_tcp; +#![deny(warnings, rust_2018_idioms)] +use env_logger; +use futures::stream::Stream; +use futures::Future; use std::io::{Read, Write}; use std::net::TcpStream; use std::thread; - -use futures::stream::Stream; -use futures::Future; use tokio_io::io::copy; use tokio_io::AsyncRead; use tokio_tcp::TcpListener; diff --git a/tokio-tcp/tests/tcp.rs b/tokio-tcp/tests/tcp.rs index 0c1aca9ba..48a0ffd48 100644 --- a/tokio-tcp/tests/tcp.rs +++ b/tokio-tcp/tests/tcp.rs @@ -1,13 +1,9 @@ -extern crate env_logger; -extern crate futures; -extern crate mio; -extern crate tokio_io; -extern crate tokio_tcp; +#![deny(warnings, rust_2018_idioms)] +use env_logger; +use futures::{Future, Stream}; use std::sync::mpsc::channel; use std::{net, thread}; - -use futures::{Future, Stream}; use tokio_tcp::{TcpListener, TcpStream}; macro_rules! t { diff --git a/tokio-test/Cargo.toml b/tokio-test/Cargo.toml index d4a8a547c..52b0113e8 100644 --- a/tokio-test/Cargo.toml +++ b/tokio-test/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-test" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.1.x" git tag. -version = "0.1.0" +# - Create "v0.2.x" git tag. +version = "0.2.0" +edition = "2018" authors = ["Tokio Contributors "] license = "MIT" repository = "https://github.com/tokio-rs/tokio" @@ -22,5 +23,5 @@ publish = false [dependencies] futures = "0.1" -tokio-timer = "0.2" -tokio-executor = "0.1" +tokio-timer = { version = "0.3.0", path = "../tokio-timer" } +tokio-executor = { version = "0.2.0", path = "../tokio-executor" } diff --git a/tokio-test/README.md b/tokio-test/README.md index cc737fb44..7e58074b6 100644 --- a/tokio-test/README.md +++ b/tokio-test/README.md @@ -17,7 +17,6 @@ Next, add this to your crate: ```rust #[macro_use] -extern crate tokio_test; ``` You can find extensive documentation and examples about how to use this crate diff --git a/tokio-test/src/clock.rs b/tokio-test/src/clock.rs index f8e964abc..75d3ad629 100644 --- a/tokio-test/src/clock.rs +++ b/tokio-test/src/clock.rs @@ -3,13 +3,12 @@ //! # Example //! //! ``` -//! # #[macro_use] extern crate tokio_test; -//! # extern crate futures; -//! # extern crate tokio_timer; -//! # use tokio_test::clock; -//! # use tokio_timer::Delay; -//! # use std::time::Duration; -//! # use futures::Future; +//! use tokio_test::clock; +//! use tokio_test::{assert_ready, assert_not_ready}; +//! use tokio_timer::Delay; +//! use std::time::Duration; +//! use futures::Future; +//! //! clock::mock(|handle| { //! let mut delay = Delay::new(handle.now() + Duration::from_secs(1)); //! diff --git a/tokio-test/src/lib.rs b/tokio-test/src/lib.rs index 1256e3c2a..256759eaa 100644 --- a/tokio-test/src/lib.rs +++ b/tokio-test/src/lib.rs @@ -1,23 +1,25 @@ #![doc(html_root_url = "https://docs.rs/tokio-test/0.1.0")] -#![deny(missing_docs, missing_debug_implementations, unreachable_pub)] +#![deny( + missing_docs, + missing_debug_implementations, + unreachable_pub, + rust_2018_idioms +)] #![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! Tokio and Futures based testing utilites //! //! # Example //! //! ``` -//! # extern crate futures; -//! # #[macro_use] extern crate tokio_test; //! # use futures::{Future, future}; +//! use tokio_test::assert_ready; +//! //! let mut fut = future::ok::<(), ()>(()); //! assert_ready!(fut.poll()); //! ``` -extern crate futures; -extern crate tokio_executor; -extern crate tokio_timer; - pub mod clock; mod macros; pub mod task; diff --git a/tokio-test/src/task.rs b/tokio-test/src/task.rs index f3d52c3dd..328d2064c 100644 --- a/tokio-test/src/task.rs +++ b/tokio-test/src/task.rs @@ -6,8 +6,7 @@ //! poll. //! //! ``` -//! # #[macro_use] extern crate tokio_test; -//! # extern crate futures; +//! # use tokio_test::assert_ready_eq; //! # use tokio_test::task::MockTask; //! # use futures::{sync::mpsc, Stream, Sink, Future, Async}; //! let mut task = MockTask::new(); @@ -20,7 +19,6 @@ use futures::executor::{spawn, Notify}; use futures::{future, Async}; - use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Condvar, Mutex}; diff --git a/tokio-test/tests/clock.rs b/tokio-test/tests/clock.rs index 6690a7cb9..a57edd72d 100644 --- a/tokio-test/tests/clock.rs +++ b/tokio-test/tests/clock.rs @@ -1,12 +1,10 @@ -#[macro_use] -extern crate tokio_test; -extern crate futures; -extern crate tokio_timer; +#![deny(warnings, rust_2018_idioms)] use futures::Future; use std::time::{Duration, Instant}; use tokio_test::clock::MockClock; use tokio_test::task::MockTask; +use tokio_test::{assert_not_ready, assert_ready}; use tokio_timer::Delay; #[test] diff --git a/tokio-threadpool/Cargo.toml b/tokio-threadpool/Cargo.toml index 39c6e1947..5fb9aa432 100644 --- a/tokio-threadpool/Cargo.toml +++ b/tokio-threadpool/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-threadpool" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.1.x" git tag. -version = "0.1.14" +# - Create "v0.2.x" git tag. +version = "0.2.0" +edition = "2018" documentation = "https://docs.rs/tokio-threadpool/0.1.14/tokio_threadpool" repository = "https://github.com/tokio-rs/tokio" homepage = "https://github.com/tokio-rs/tokio" @@ -19,9 +20,10 @@ A task scheduler backed by a work-stealing thread pool. """ keywords = ["futures", "tokio"] categories = ["concurrency", "asynchronous"] +publish = false [dependencies] -tokio-executor = "0.1.7" +tokio-executor = { version = "0.2.0", path = "../tokio-executor" } futures = "0.1.19" crossbeam-deque = "0.7.0" crossbeam-queue = "0.1.0" diff --git a/tokio-threadpool/README.md b/tokio-threadpool/README.md index 9d250439f..103b13ea4 100644 --- a/tokio-threadpool/README.md +++ b/tokio-threadpool/README.md @@ -24,9 +24,6 @@ It's 10x slower. ## Examples ```rust -extern crate tokio_threadpool; -extern crate futures; - use tokio_threadpool::ThreadPool; use futures::{Future, lazy}; use futures::sync::oneshot; diff --git a/tokio-threadpool/benches/basic.rs b/tokio-threadpool/benches/basic.rs index 70dee74f5..c49f6a8e4 100644 --- a/tokio-threadpool/benches/basic.rs +++ b/tokio-threadpool/benches/basic.rs @@ -1,11 +1,7 @@ #![feature(test)] -#![deny(warnings)] +#![deny(warnings, rust_2018_idioms)] -extern crate futures; -extern crate futures_cpupool; -extern crate num_cpus; extern crate test; -extern crate tokio_threadpool; const NUM_SPAWN: usize = 10_000; const NUM_YIELD: usize = 1_000; @@ -17,7 +13,6 @@ mod threadpool { use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use std::sync::{mpsc, Arc}; - use test; use tokio_threadpool::*; #[bench] @@ -97,7 +92,6 @@ mod cpupool { use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use std::sync::{mpsc, Arc}; - use test; #[bench] fn spawn_many(b: &mut test::Bencher) { diff --git a/tokio-threadpool/benches/blocking.rs b/tokio-threadpool/benches/blocking.rs index 8ea900eaa..7dfad5d66 100644 --- a/tokio-threadpool/benches/blocking.rs +++ b/tokio-threadpool/benches/blocking.rs @@ -1,17 +1,12 @@ #![feature(test)] -#![deny(warnings)] +#![deny(warnings, rust_2018_idioms)] -extern crate futures; -extern crate rand; extern crate test; -extern crate threadpool; -extern crate tokio_threadpool; const ITER: usize = 1_000; mod blocking { use super::*; - use futures::future::*; use tokio_threadpool::{blocking, Builder}; @@ -20,9 +15,9 @@ mod blocking { let pool = Builder::new().pool_size(2).max_blocking(20).build(); b.iter(|| { - let count_down = Arc::new(CountDown::new(::ITER)); + let count_down = Arc::new(CountDown::new(ITER)); - for _ in 0..::ITER { + for _ in 0..ITER { let count_down = count_down.clone(); pool.spawn(lazy(move || { @@ -42,7 +37,6 @@ mod blocking { mod message_passing { use super::*; - use futures::future::*; use futures::sync::oneshot; use tokio_threadpool::Builder; @@ -54,9 +48,9 @@ mod message_passing { let blocking = threadpool::ThreadPool::new(20); b.iter(|| { - let count_down = Arc::new(CountDown::new(::ITER)); + let count_down = Arc::new(CountDown::new(ITER)); - for _ in 0..::ITER { + for _ in 0..ITER { let count_down = count_down.clone(); let blocking = blocking.clone(); diff --git a/tokio-threadpool/benches/depth.rs b/tokio-threadpool/benches/depth.rs index 2d89ac90d..3d5a1c80a 100644 --- a/tokio-threadpool/benches/depth.rs +++ b/tokio-threadpool/benches/depth.rs @@ -1,18 +1,13 @@ #![feature(test)] -#![deny(warnings)] +#![deny(warnings, rust_2018_idioms)] -extern crate futures; -extern crate futures_cpupool; -extern crate num_cpus; extern crate test; -extern crate tokio_threadpool; const ITER: usize = 20_000; mod us { use futures::future; use std::sync::mpsc; - use test; use tokio_threadpool::*; #[bench] @@ -47,7 +42,6 @@ mod cpupool { use futures_cpupool::*; use num_cpus; use std::sync::mpsc; - use test; #[bench] fn chained_spawn(b: &mut test::Bencher) { diff --git a/tokio-threadpool/src/blocking.rs b/tokio-threadpool/src/blocking.rs index 9f91234b9..094612049 100644 --- a/tokio-threadpool/src/blocking.rs +++ b/tokio-threadpool/src/blocking.rs @@ -1,7 +1,5 @@ -use worker::Worker; - -use futures::Poll; - +use crate::worker::Worker; +use futures::{try_ready, Poll}; use std::error::Error; use std::fmt; @@ -80,9 +78,6 @@ pub struct BlockingError { /// that needs to be performed. /// /// ```rust -/// # extern crate futures; -/// # extern crate tokio_threadpool; -/// /// use tokio_threadpool::{ThreadPool, blocking}; /// /// use futures::Future; @@ -157,13 +152,13 @@ where } impl fmt::Display for BlockingError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{}", self.description()) } } impl fmt::Debug for BlockingError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("BlockingError") .field("reason", &self.description()) .finish() diff --git a/tokio-threadpool/src/builder.rs b/tokio-threadpool/src/builder.rs index a51e8e520..2f4ff94a8 100644 --- a/tokio-threadpool/src/builder.rs +++ b/tokio-threadpool/src/builder.rs @@ -1,20 +1,19 @@ -use callback::Callback; -use config::{Config, MAX_WORKERS}; -use park::{BoxPark, BoxedPark, DefaultPark}; -use pool::{Pool, MAX_BACKUP}; -use shutdown::ShutdownTrigger; -use thread_pool::ThreadPool; -use worker::{self, Worker, WorkerId}; - +use crate::callback::Callback; +use crate::config::{Config, MAX_WORKERS}; +use crate::park::{BoxPark, BoxedPark, DefaultPark}; +use crate::pool::{Pool, MAX_BACKUP}; +use crate::shutdown::ShutdownTrigger; +use crate::thread_pool::ThreadPool; +use crate::worker::{self, Worker, WorkerId}; +use crossbeam_deque::Injector; +use log::trace; +use num_cpus; use std::any::Any; use std::cmp::max; use std::error::Error; use std::fmt; use std::sync::Arc; use std::time::Duration; - -use crossbeam_deque::Injector; -use num_cpus; use tokio_executor::park::Park; use tokio_executor::Enter; @@ -34,13 +33,10 @@ use tokio_executor::Enter; /// # Examples /// /// ``` -/// # extern crate tokio_threadpool; -/// # extern crate futures; -/// # use tokio_threadpool::Builder; +/// use tokio_threadpool::Builder; /// use futures::future::{Future, lazy}; /// use std::time::Duration; /// -/// # pub fn main() { /// let thread_pool = Builder::new() /// .pool_size(4) /// .keep_alive(Some(Duration::from_secs(30))) @@ -53,7 +49,6 @@ use tokio_executor::Enter; /// /// // Gracefully shutdown the threadpool /// thread_pool.shutdown().wait().unwrap(); -/// # } /// ``` pub struct Builder { /// Thread pool specific configuration values @@ -67,7 +62,7 @@ pub struct Builder { max_blocking: usize, /// Generates the `Park` instances - new_park: Box BoxPark>, + new_park: Box BoxPark>, } impl Builder { @@ -79,17 +74,13 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio_threadpool; - /// # extern crate futures; - /// # use tokio_threadpool::Builder; + /// use tokio_threadpool::Builder; /// use std::time::Duration; /// - /// # pub fn main() { /// let thread_pool = Builder::new() /// .pool_size(4) /// .keep_alive(Some(Duration::from_secs(30))) /// .build(); - /// # } /// ``` pub fn new() -> Builder { let num_cpus = max(1, num_cpus::get()); @@ -123,15 +114,11 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio_threadpool; - /// # extern crate futures; - /// # use tokio_threadpool::Builder; + /// use tokio_threadpool::Builder; /// - /// # pub fn main() { /// let thread_pool = Builder::new() /// .pool_size(4) /// .build(); - /// # } /// ``` pub fn pool_size(&mut self, val: usize) -> &mut Self { assert!(val >= 1, "at least one thread required"); @@ -155,15 +142,11 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio_threadpool; - /// # extern crate futures; - /// # use tokio_threadpool::Builder; + /// use tokio_threadpool::Builder; /// - /// # pub fn main() { /// let thread_pool = Builder::new() /// .max_blocking(200) /// .build(); - /// # } /// ``` pub fn max_blocking(&mut self, val: usize) -> &mut Self { assert!(val <= MAX_BACKUP, "max value is {}", MAX_BACKUP); @@ -185,16 +168,12 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio_threadpool; - /// # extern crate futures; - /// # use tokio_threadpool::Builder; + /// use tokio_threadpool::Builder; /// use std::time::Duration; /// - /// # pub fn main() { /// let thread_pool = Builder::new() /// .keep_alive(Some(Duration::from_secs(30))) /// .build(); - /// # } /// ``` pub fn keep_alive(&mut self, val: Option) -> &mut Self { self.config.keep_alive = val; @@ -211,19 +190,15 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio_threadpool; - /// # extern crate futures; - /// # use tokio_threadpool::Builder; + /// use tokio_threadpool::Builder; /// - /// # pub fn main() { /// let thread_pool = Builder::new() /// .panic_handler(|err| std::panic::resume_unwind(err)) /// .build(); - /// # } /// ``` pub fn panic_handler(&mut self, f: F) -> &mut Self where - F: Fn(Box) + Send + Sync + 'static, + F: Fn(Box) + Send + Sync + 'static, { self.config.panic_handler = Some(Arc::new(f)); self @@ -241,15 +216,11 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio_threadpool; - /// # extern crate futures; - /// # use tokio_threadpool::Builder; + /// use tokio_threadpool::Builder; /// - /// # pub fn main() { /// let thread_pool = Builder::new() /// .name_prefix("my-pool-") /// .build(); - /// # } /// ``` pub fn name_prefix>(&mut self, val: S) -> &mut Self { self.config.name_prefix = Some(val.into()); @@ -267,15 +238,11 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio_threadpool; - /// # extern crate futures; - /// # use tokio_threadpool::Builder; + /// use tokio_threadpool::Builder; /// - /// # pub fn main() { /// let thread_pool = Builder::new() /// .stack_size(32 * 1024) /// .build(); - /// # } /// ``` pub fn stack_size(&mut self, val: usize) -> &mut Self { self.config.stack_size = Some(val); @@ -291,11 +258,8 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio_threadpool; - /// # extern crate futures; - /// # use tokio_threadpool::Builder; + /// use tokio_threadpool::Builder; /// - /// # pub fn main() { /// let thread_pool = Builder::new() /// .around_worker(|worker, _| { /// println!("worker is starting up"); @@ -303,7 +267,6 @@ impl Builder { /// println!("worker is shutting down"); /// }) /// .build(); - /// # } /// ``` /// /// [`Worker::run`]: struct.Worker.html#method.run @@ -323,17 +286,13 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio_threadpool; - /// # extern crate futures; - /// # use tokio_threadpool::Builder; + /// use tokio_threadpool::Builder; /// - /// # pub fn main() { /// let thread_pool = Builder::new() /// .after_start(|| { /// println!("thread started"); /// }) /// .build(); - /// # } /// ``` pub fn after_start(&mut self, f: F) -> &mut Self where @@ -350,17 +309,13 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio_threadpool; - /// # extern crate futures; - /// # use tokio_threadpool::Builder; + /// use tokio_threadpool::Builder; /// - /// # pub fn main() { /// let thread_pool = Builder::new() /// .before_stop(|| { /// println!("thread stopping"); /// }) /// .build(); - /// # } /// ``` pub fn before_stop(&mut self, f: F) -> &mut Self where @@ -378,12 +333,9 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio_threadpool; - /// # extern crate futures; - /// # use tokio_threadpool::Builder; + /// use tokio_threadpool::Builder; /// # fn decorate(f: F) -> F { f } /// - /// # pub fn main() { /// let thread_pool = Builder::new() /// .custom_park(|_| { /// use tokio_threadpool::park::DefaultPark; @@ -397,7 +349,6 @@ impl Builder { /// decorate(park) /// }) /// .build(); - /// # } /// ``` pub fn custom_park(&mut self, f: F) -> &mut Self where @@ -417,14 +368,10 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio_threadpool; - /// # extern crate futures; - /// # use tokio_threadpool::Builder; + /// use tokio_threadpool::Builder; /// - /// # pub fn main() { /// let thread_pool = Builder::new() /// .build(); - /// # } /// ``` pub fn build(&self) -> ThreadPool { trace!("build; num-workers={}", self.pool_size); @@ -466,7 +413,7 @@ impl Builder { } impl fmt::Debug for Builder { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Builder") .field("config", &self.config) .field("pool_size", &self.pool_size) diff --git a/tokio-threadpool/src/callback.rs b/tokio-threadpool/src/callback.rs index aabf876f4..7ad765a10 100644 --- a/tokio-threadpool/src/callback.rs +++ b/tokio-threadpool/src/callback.rs @@ -1,13 +1,11 @@ -use worker::Worker; - +use crate::worker::Worker; use std::fmt; use std::sync::Arc; - use tokio_executor::Enter; #[derive(Clone)] pub(crate) struct Callback { - f: Arc, + f: Arc, } impl Callback { @@ -24,7 +22,7 @@ impl Callback { } impl fmt::Debug for Callback { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "Fn") } } diff --git a/tokio-threadpool/src/config.rs b/tokio-threadpool/src/config.rs index 5cbd0156e..42fa13dda 100644 --- a/tokio-threadpool/src/config.rs +++ b/tokio-threadpool/src/config.rs @@ -1,5 +1,4 @@ -use callback::Callback; - +use crate::callback::Callback; use std::any::Any; use std::fmt; use std::sync::Arc; @@ -13,9 +12,9 @@ pub(crate) struct Config { pub name_prefix: Option, pub stack_size: Option, pub around_worker: Option, - pub after_start: Option>, - pub before_stop: Option>, - pub panic_handler: Option) + Send + Sync>>, + pub after_start: Option>, + pub before_stop: Option>, + pub panic_handler: Option) + Send + Sync>>, } /// Max number of workers that can be part of a pool. This is the most that can @@ -24,7 +23,7 @@ pub(crate) struct Config { pub(crate) const MAX_WORKERS: usize = 1 << 15; impl fmt::Debug for Config { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Config") .field("keep_alive", &self.keep_alive) .field("name_prefix", &self.name_prefix) diff --git a/tokio-threadpool/src/lib.rs b/tokio-threadpool/src/lib.rs index 922a3f4d9..2aff652be 100644 --- a/tokio-threadpool/src/lib.rs +++ b/tokio-threadpool/src/lib.rs @@ -1,5 +1,7 @@ #![doc(html_root_url = "https://docs.rs/tokio-threadpool/0.1.14")] -#![deny(warnings, missing_docs, missing_debug_implementations)] +#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! A work-stealing based thread pool for executing futures. //! @@ -77,20 +79,6 @@ //! [`blocking`]: fn.blocking.html //! [`runtime`]: https://docs.rs/tokio/0.1/tokio/runtime/ -extern crate tokio_executor; - -extern crate crossbeam_deque; -extern crate crossbeam_queue; -extern crate crossbeam_utils; -#[macro_use] -extern crate futures; -extern crate num_cpus; -extern crate rand; -extern crate slab; - -#[macro_use] -extern crate log; - // ## Crate layout // // The primary type, `Pool`, holds the majority of a thread pool's state, @@ -155,9 +143,9 @@ mod task; mod thread_pool; mod worker; -pub use blocking::{blocking, BlockingError}; -pub use builder::Builder; -pub use sender::Sender; -pub use shutdown::Shutdown; -pub use thread_pool::{SpawnHandle, ThreadPool}; -pub use worker::{Worker, WorkerId}; +pub use crate::blocking::{blocking, BlockingError}; +pub use crate::builder::Builder; +pub use crate::sender::Sender; +pub use crate::shutdown::Shutdown; +pub use crate::thread_pool::{SpawnHandle, ThreadPool}; +pub use crate::worker::{Worker, WorkerId}; diff --git a/tokio-threadpool/src/notifier.rs b/tokio-threadpool/src/notifier.rs index fe8e8f4ad..ed1429744 100644 --- a/tokio-threadpool/src/notifier.rs +++ b/tokio-threadpool/src/notifier.rs @@ -1,12 +1,11 @@ -use pool::Pool; -use task::Task; - +use crate::pool::Pool; +use crate::task::Task; +use futures::executor::Notify; +use log::trace; use std::mem; use std::ops; use std::sync::Arc; -use futures::executor::Notify; - /// Implements the future `Notify` API. /// /// This is how external events are able to signal the task, informing it to try diff --git a/tokio-threadpool/src/park/boxed.rs b/tokio-threadpool/src/park/boxed.rs index 8beaa0bb5..d4daf8333 100644 --- a/tokio-threadpool/src/park/boxed.rs +++ b/tokio-threadpool/src/park/boxed.rs @@ -1,10 +1,10 @@ -use tokio_executor::park::{Park, Unpark}; - +use log::warn; use std::error::Error; use std::time::Duration; +use tokio_executor::park::{Park, Unpark}; -pub(crate) type BoxPark = Box + Send>; -pub(crate) type BoxUnpark = Box; +pub(crate) type BoxPark = Box + Send>; +pub(crate) type BoxUnpark = Box; pub(crate) struct BoxedPark(T); diff --git a/tokio-threadpool/src/park/default_park.rs b/tokio-threadpool/src/park/default_park.rs index ecc22350f..ad97f8892 100644 --- a/tokio-threadpool/src/park/default_park.rs +++ b/tokio-threadpool/src/park/default_park.rs @@ -1,10 +1,8 @@ -use tokio_executor::park::{Park, Unpark}; - +use crossbeam_utils::sync::{Parker, Unparker}; use std::error::Error; use std::fmt; use std::time::Duration; - -use crossbeam_utils::sync::{Parker, Unparker}; +use tokio_executor::park::{Park, Unpark}; /// Parks the thread. #[derive(Debug)] @@ -85,7 +83,7 @@ impl Unpark for DefaultUnpark { // ===== impl ParkError ===== impl fmt::Display for ParkError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { self.description().fmt(fmt) } } diff --git a/tokio-threadpool/src/pool/backup.rs b/tokio-threadpool/src/pool/backup.rs index e94e95d6f..cb7f7ff5c 100644 --- a/tokio-threadpool/src/pool/backup.rs +++ b/tokio-threadpool/src/pool/backup.rs @@ -1,5 +1,5 @@ -use park::DefaultPark; -use worker::WorkerId; +use crate::park::DefaultPark; +use crate::worker::WorkerId; use std::cell::UnsafeCell; use std::fmt; @@ -298,7 +298,7 @@ impl From for usize { } impl fmt::Debug for State { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("backup::State") .field("is_pushed", &self.is_pushed()) .field("is_running", &self.is_running()) diff --git a/tokio-threadpool/src/pool/backup_stack.rs b/tokio-threadpool/src/pool/backup_stack.rs index b9a46d08e..0c3af3755 100644 --- a/tokio-threadpool/src/pool/backup_stack.rs +++ b/tokio-threadpool/src/pool/backup_stack.rs @@ -1,4 +1,4 @@ -use pool::{Backup, BackupId}; +use crate::pool::{Backup, BackupId}; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::{AcqRel, Acquire}; diff --git a/tokio-threadpool/src/pool/mod.rs b/tokio-threadpool/src/pool/mod.rs index 929178354..793b5b5e3 100644 --- a/tokio-threadpool/src/pool/mod.rs +++ b/tokio-threadpool/src/pool/mod.rs @@ -9,13 +9,15 @@ pub(crate) use self::state::{Lifecycle, State, MAX_FUTURES}; use self::backup::Handoff; use self::backup_stack::BackupStack; -use config::Config; -use shutdown::ShutdownTrigger; -use task::{Blocking, Task}; -use worker::{self, Worker, WorkerId}; - +use crate::config::Config; +use crate::shutdown::ShutdownTrigger; +use crate::task::{Blocking, Task}; +use crate::worker::{self, Worker, WorkerId}; +use crossbeam_deque::Injector; +use crossbeam_utils::CachePadded; use futures::Poll; - +use log::{debug, error, trace}; +use rand; use std::cell::Cell; use std::num::Wrapping; use std::sync::atomic::AtomicUsize; @@ -23,10 +25,6 @@ use std::sync::atomic::Ordering::{AcqRel, Acquire}; use std::sync::{Arc, Weak}; use std::thread; -use crossbeam_deque::Injector; -use crossbeam_utils::CachePadded; -use rand; - #[derive(Debug)] pub(crate) struct Pool { // Tracks the state of the thread pool (running, shutting down, ...). @@ -202,7 +200,7 @@ impl Pool { } pub fn terminate_sleeping_workers(&self) { - use worker::Lifecycle::Signaled; + use crate::worker::Lifecycle::Signaled; trace!(" -> shutting down workers"); // Wakeup all sleeping workers. They will wake up, see the state @@ -221,7 +219,7 @@ impl Pool { } } - pub fn poll_blocking_capacity(&self, task: &Arc) -> Poll<(), ::BlockingError> { + pub fn poll_blocking_capacity(&self, task: &Arc) -> Poll<(), crate::BlockingError> { self.blocking.poll_blocking_capacity(task) } @@ -395,7 +393,7 @@ impl Pool { pub fn signal_work(&self, pool: &Arc) { debug_assert_eq!(*self, **pool); - use worker::Lifecycle::Signaled; + use crate::worker::Lifecycle::Signaled; if let Some((idx, worker_state)) = self.sleep_stack.pop(&self.workers, Signaled, false) { let entry = &self.workers[idx]; diff --git a/tokio-threadpool/src/pool/state.rs b/tokio-threadpool/src/pool/state.rs index 5ecb514e5..8806c9566 100644 --- a/tokio-threadpool/src/pool/state.rs +++ b/tokio-threadpool/src/pool/state.rs @@ -99,7 +99,7 @@ impl From for usize { } impl fmt::Debug for State { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("pool::State") .field("lifecycle", &self.lifecycle()) .field("num_futures", &self.num_futures()) diff --git a/tokio-threadpool/src/sender.rs b/tokio-threadpool/src/sender.rs index fadd0cba3..ef79bed99 100644 --- a/tokio-threadpool/src/sender.rs +++ b/tokio-threadpool/src/sender.rs @@ -1,10 +1,9 @@ -use pool::{self, Lifecycle, Pool, MAX_FUTURES}; -use task::Task; - +use crate::pool::{self, Lifecycle, Pool, MAX_FUTURES}; +use crate::task::Task; +use futures::{future, Future}; +use log::trace; use std::sync::atomic::Ordering::{AcqRel, Acquire}; use std::sync::Arc; - -use futures::{future, Future}; use tokio_executor::{self, SpawnError}; /// Submit futures to the associated thread pool for execution. @@ -58,8 +57,6 @@ impl Sender { /// # Examples /// /// ```rust - /// # extern crate tokio_threadpool; - /// # extern crate futures; /// # use tokio_threadpool::ThreadPool; /// use futures::future::{Future, lazy}; /// @@ -131,7 +128,7 @@ impl tokio_executor::Executor for Sender { fn spawn( &mut self, - future: Box + Send>, + future: Box + Send>, ) -> Result<(), SpawnError> { let mut s = &*self; tokio_executor::Executor::spawn(&mut s, future) @@ -157,7 +154,7 @@ impl<'a> tokio_executor::Executor for &'a Sender { fn spawn( &mut self, - future: Box + Send>, + future: Box + Send>, ) -> Result<(), SpawnError> { self.prepare_for_spawn()?; diff --git a/tokio-threadpool/src/shutdown.rs b/tokio-threadpool/src/shutdown.rs index c3d04a002..925f7e44a 100644 --- a/tokio-threadpool/src/shutdown.rs +++ b/tokio-threadpool/src/shutdown.rs @@ -1,10 +1,8 @@ -use task::Task; -use worker; - +use crate::task::Task; +use crate::worker; use crossbeam_deque::Injector; use futures::task::AtomicTask; use futures::{Async, Future, Poll}; - use std::sync::{Arc, Mutex}; /// Future that resolves when the thread pool is shutdown. diff --git a/tokio-threadpool/src/task/blocking.rs b/tokio-threadpool/src/task/blocking.rs index ded59edfe..77a175b2a 100644 --- a/tokio-threadpool/src/task/blocking.rs +++ b/tokio-threadpool/src/task/blocking.rs @@ -1,8 +1,6 @@ -use pool::Pool; -use task::{BlockingState, Task}; - +use crate::pool::Pool; +use crate::task::{BlockingState, Task}; use futures::{Async, Poll}; - use std::cell::UnsafeCell; use std::fmt; use std::ptr; @@ -111,7 +109,7 @@ impl Blocking { /// /// The caller must ensure that `task` has not previously been queued to be /// notified when capacity becomes available. - pub fn poll_blocking_capacity(&self, task: &Arc) -> Poll<(), ::BlockingError> { + pub fn poll_blocking_capacity(&self, task: &Arc) -> Poll<(), crate::BlockingError> { // This requires atomically claiming blocking capacity and if none is // available, queuing &task. @@ -482,7 +480,7 @@ impl From for usize { } impl fmt::Debug for State { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut fmt = fmt.debug_struct("State"); if self.is_ptr() { diff --git a/tokio-threadpool/src/task/blocking_state.rs b/tokio-threadpool/src/task/blocking_state.rs index b41fc4868..36f49d038 100644 --- a/tokio-threadpool/src/task/blocking_state.rs +++ b/tokio-threadpool/src/task/blocking_state.rs @@ -1,5 +1,4 @@ -use task::CanBlock; - +use crate::task::CanBlock; use std::fmt; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -80,7 +79,7 @@ impl From for usize { } impl fmt::Debug for BlockingState { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("BlockingState") .field("is_queued", &self.is_queued()) .field("is_allocated", &self.is_allocated()) diff --git a/tokio-threadpool/src/task/mod.rs b/tokio-threadpool/src/task/mod.rs index d9bdb07a4..7af070dd4 100644 --- a/tokio-threadpool/src/task/mod.rs +++ b/tokio-threadpool/src/task/mod.rs @@ -5,13 +5,11 @@ mod state; pub(crate) use self::blocking::{Blocking, CanBlock}; use self::blocking_state::BlockingState; use self::state::State; - -use notifier::Notifier; -use pool::Pool; - +use crate::notifier::Notifier; +use crate::pool::Pool; use futures::executor::{self, Spawn}; use futures::{self, Async, Future}; - +use log::trace; use std::cell::{Cell, UnsafeCell}; use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release}; use std::sync::atomic::{AtomicPtr, AtomicUsize}; @@ -60,7 +58,7 @@ pub(crate) enum Run { Complete, } -type BoxFuture = Box + Send + 'static>; +type BoxFuture = Box + Send + 'static>; // ===== impl Task ===== @@ -299,7 +297,7 @@ impl Task { } impl fmt::Debug for Task { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Task") .field("state", &self.state) .field("future", &"Spawn") diff --git a/tokio-threadpool/src/thread_pool.rs b/tokio-threadpool/src/thread_pool.rs index 30f58e96a..62abd1e73 100644 --- a/tokio-threadpool/src/thread_pool.rs +++ b/tokio-threadpool/src/thread_pool.rs @@ -1,11 +1,9 @@ -use builder::Builder; -use pool::Pool; -use sender::Sender; -use shutdown::{Shutdown, ShutdownTrigger}; - +use crate::builder::Builder; +use crate::pool::Pool; +use crate::sender::Sender; +use crate::shutdown::{Shutdown, ShutdownTrigger}; use futures::sync::oneshot; use futures::{Future, Poll}; - use std::sync::Arc; /// Work-stealing based thread pool for executing futures. @@ -53,12 +51,9 @@ impl ThreadPool { /// # Examples /// /// ```rust - /// # extern crate tokio_threadpool; - /// # extern crate futures; /// # use tokio_threadpool::ThreadPool; /// use futures::future::{Future, lazy}; /// - /// # pub fn main() { /// // Create a thread pool with default configuration values /// let thread_pool = ThreadPool::new(); /// @@ -69,7 +64,6 @@ impl ThreadPool { /// /// // Gracefully shutdown the threadpool /// thread_pool.shutdown().wait().unwrap(); - /// # } /// ``` /// /// # Panics @@ -93,12 +87,9 @@ impl ThreadPool { /// # Examples /// /// ```rust - /// # extern crate tokio_threadpool; - /// # extern crate futures; /// # use tokio_threadpool::ThreadPool; /// use futures::future::{Future, lazy}; /// - /// # pub fn main() { /// // Create a thread pool with default configuration values /// let thread_pool = ThreadPool::new(); /// @@ -109,7 +100,6 @@ impl ThreadPool { /// /// // Gracefully shutdown the threadpool /// thread_pool.shutdown().wait().unwrap(); - /// # } /// ``` /// /// # Panics diff --git a/tokio-threadpool/src/worker/entry.rs b/tokio-threadpool/src/worker/entry.rs index 0dcf5108b..199b9ba16 100644 --- a/tokio-threadpool/src/worker/entry.rs +++ b/tokio-threadpool/src/worker/entry.rs @@ -1,7 +1,10 @@ -use park::{BoxPark, BoxUnpark}; -use task::Task; -use worker::state::{State, PUSHED_MASK}; - +use crate::park::{BoxPark, BoxUnpark}; +use crate::task::Task; +use crate::worker::state::{State, PUSHED_MASK}; +use crossbeam_deque::{Steal, Stealer, Worker}; +use crossbeam_queue::SegQueue; +use crossbeam_utils::CachePadded; +use slab::Slab; use std::cell::UnsafeCell; use std::fmt; use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release}; @@ -9,11 +12,6 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; -use crossbeam_deque::{Steal, Stealer, Worker}; -use crossbeam_queue::SegQueue; -use crossbeam_utils::CachePadded; -use slab::Slab; - // TODO: None of the fields should be public // // It would also be helpful to split up the state across what fields / @@ -96,7 +94,7 @@ impl WorkerEntry { /// The `state` must have been obtained with an `Acquire` ordering. #[inline] pub fn notify(&self, mut state: State) -> bool { - use worker::Lifecycle::*; + use crate::worker::Lifecycle::*; loop { let mut next = state; @@ -141,7 +139,7 @@ impl WorkerEntry { /// /// Returns `Err` if the worker has already terminated. pub fn signal_stop(&self, mut state: State) { - use worker::Lifecycle::*; + use crate::worker::Lifecycle::*; // Transition the worker state to signaled loop { @@ -317,7 +315,7 @@ impl WorkerEntry { } impl fmt::Debug for WorkerEntry { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("WorkerEntry") .field("state", &self.state.load(Relaxed)) .field("next_sleeper", &"UnsafeCell") diff --git a/tokio-threadpool/src/worker/mod.rs b/tokio-threadpool/src/worker/mod.rs index d380c5d56..9165f3945 100644 --- a/tokio-threadpool/src/worker/mod.rs +++ b/tokio-threadpool/src/worker/mod.rs @@ -6,16 +6,13 @@ pub(crate) use self::entry::WorkerEntry as Entry; pub(crate) use self::stack::Stack; pub(crate) use self::state::{Lifecycle, State}; -use notifier::Notifier; -use pool::{self, BackupId, Pool}; -use sender::Sender; -use shutdown::ShutdownTrigger; -use task::{self, CanBlock, Task}; - -use tokio_executor; - +use crate::notifier::Notifier; +use crate::pool::{self, BackupId, Pool}; +use crate::sender::Sender; +use crate::shutdown::ShutdownTrigger; +use crate::task::{self, CanBlock, Task}; use futures::{Async, Poll}; - +use log::trace; use std::cell::Cell; use std::marker::PhantomData; use std::rc::Rc; @@ -23,6 +20,7 @@ use std::sync::atomic::Ordering::{AcqRel, Acquire}; use std::sync::Arc; use std::thread; use std::time::Duration; +use tokio_executor; /// Thread worker /// @@ -150,7 +148,7 @@ impl Worker { } /// Transition the current worker to a blocking worker - pub(crate) fn transition_to_blocking(&self) -> Poll<(), ::BlockingError> { + pub(crate) fn transition_to_blocking(&self) -> Poll<(), crate::BlockingError> { use self::CanBlock::*; // If we get this far, then `current_task` has been set. @@ -447,7 +445,7 @@ impl Worker { } fn run_task(&self, task: Arc, notify: &Arc) { - use task::Run::*; + use crate::task::Run::*; // If this is the first time this task is being polled, register it so that we can keep // track of tasks that are in progress. diff --git a/tokio-threadpool/src/worker/stack.rs b/tokio-threadpool/src/worker/stack.rs index d02c277fe..2d02864a3 100644 --- a/tokio-threadpool/src/worker/stack.rs +++ b/tokio-threadpool/src/worker/stack.rs @@ -1,6 +1,5 @@ -use config::MAX_WORKERS; -use worker; - +use crate::config::MAX_WORKERS; +use crate::worker; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed}; use std::{fmt, usize}; @@ -242,7 +241,7 @@ impl From for usize { } impl fmt::Debug for State { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let head = self.head(); let mut fmt = fmt.debug_struct("stack::State"); diff --git a/tokio-threadpool/src/worker/state.rs b/tokio-threadpool/src/worker/state.rs index c388f6c99..82789eb3d 100644 --- a/tokio-threadpool/src/worker/state.rs +++ b/tokio-threadpool/src/worker/state.rs @@ -93,7 +93,7 @@ impl From for usize { } impl fmt::Debug for State { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("worker::State") .field("lifecycle", &self.lifecycle()) .field("is_pushed", &self.is_pushed()) diff --git a/tokio-threadpool/tests/blocking.rs b/tokio-threadpool/tests/blocking.rs index 5fae2af27..e3c2576fb 100644 --- a/tokio-threadpool/tests/blocking.rs +++ b/tokio-threadpool/tests/blocking.rs @@ -1,20 +1,14 @@ -extern crate tokio_threadpool; - -extern crate env_logger; -extern crate futures; -extern crate rand; - -use tokio_threadpool::*; +#![deny(warnings, rust_2018_idioms)] use futures::future::{lazy, poll_fn}; use futures::*; use rand::*; - use std::sync::atomic::Ordering::*; use std::sync::atomic::*; use std::sync::*; use std::thread; use std::time::Duration; +use tokio_threadpool::*; #[test] fn basic() { diff --git a/tokio-threadpool/tests/hammer.rs b/tokio-threadpool/tests/hammer.rs index d9ee41ca6..71db21921 100644 --- a/tokio-threadpool/tests/hammer.rs +++ b/tokio-threadpool/tests/hammer.rs @@ -1,13 +1,10 @@ -extern crate futures; -extern crate tokio_threadpool; - -use tokio_threadpool::*; +#![deny(warnings, rust_2018_idioms)] use futures::{Future, Poll, Sink, Stream}; - use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::*; use std::sync::Arc; +use tokio_threadpool::*; #[test] fn hammer() { diff --git a/tokio-threadpool/tests/threadpool.rs b/tokio-threadpool/tests/threadpool.rs index 507fd03ea..9b8b8c0f8 100644 --- a/tokio-threadpool/tests/threadpool.rs +++ b/tokio-threadpool/tests/threadpool.rs @@ -1,24 +1,21 @@ -extern crate env_logger; -extern crate futures; -extern crate tokio_executor; -extern crate tokio_threadpool; - -use tokio_executor::park::{Park, Unpark}; -use tokio_threadpool::park::{DefaultPark, DefaultUnpark}; -use tokio_threadpool::*; +#![deny(warnings, rust_2018_idioms)] use futures::future::lazy; use futures::{Async, Future, Poll, Sink, Stream}; - use std::cell::Cell; use std::sync::atomic::Ordering::Relaxed; use std::sync::atomic::*; use std::sync::{mpsc, Arc}; use std::time::Duration; +use tokio_executor::park::{Park, Unpark}; +use tokio_threadpool::park::{DefaultPark, DefaultUnpark}; +use tokio_threadpool::*; thread_local!(static FOO: Cell = Cell::new(0)); -fn ignore_results(f: F) -> Box + Send> { +fn ignore_results( + f: F, +) -> Box + Send> { Box::new(f.map(|_| ()).map_err(|_| ())) } @@ -129,7 +126,7 @@ fn force_shutdown_drops_futures() { b.fetch_add(1, Relaxed); }) .build(); - let mut tx = pool.sender().clone(); + let tx = pool.sender().clone(); tx.spawn(Never(num_drop.clone())).unwrap(); @@ -188,7 +185,7 @@ fn drop_threadpool_drops_futures() { b.fetch_add(1, Relaxed); }) .build(); - let mut tx = pool.sender().clone(); + let tx = pool.sender().clone(); tx.spawn(Never(num_drop.clone())).unwrap(); @@ -217,7 +214,7 @@ fn many_oneshot_futures() { for _ in 0..50 { let pool = ThreadPool::new(); - let mut tx = pool.sender().clone(); + let tx = pool.sender().clone(); let cnt = Arc::new(AtomicUsize::new(0)); for _ in 0..NUM { @@ -249,7 +246,7 @@ fn many_multishot_futures() { for _ in 0..50 { let pool = ThreadPool::new(); - let mut pool_tx = pool.sender().clone(); + let pool_tx = pool.sender().clone(); let mut start_txs = Vec::with_capacity(TRACKS); let mut final_rxs = Vec::with_capacity(TRACKS); diff --git a/tokio-timer/Cargo.toml b/tokio-timer/Cargo.toml index 6d13ac724..eac11d3a6 100644 --- a/tokio-timer/Cargo.toml +++ b/tokio-timer/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-timer" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.2.x" git tag. -version = "0.2.10" +# - Create "v0.3.x" git tag. +version = "0.3.0" +edition = "2018" authors = ["Carl Lerche "] license = "MIT" readme = "README.md" @@ -18,10 +19,11 @@ homepage = "https://github.com/tokio-rs/tokio" description = """ Timer facilities for Tokio """ +publish = false [dependencies] futures = "0.1.19" -tokio-executor = "0.1.1" +tokio-executor = { version = "0.2.0", path = "../tokio-executor" } crossbeam-utils = "0.6.0" # Backs `DelayQueue` @@ -30,4 +32,4 @@ slab = "0.4.1" [dev-dependencies] rand = "0.6" tokio-mock-task = "0.1.0" -tokio = "0.1.7" +tokio = { version = "0.2.0", path = "../tokio" } diff --git a/tokio-timer/src/clock/clock.rs b/tokio-timer/src/clock/clock.rs index 9b9de89ef..a4c4a0f37 100644 --- a/tokio-timer/src/clock/clock.rs +++ b/tokio-timer/src/clock/clock.rs @@ -1,12 +1,10 @@ -use clock::Now; -use timer; - -use tokio_executor::Enter; - +use crate::clock::Now; +use crate::timer; use std::cell::Cell; use std::fmt; use std::sync::Arc; use std::time::Instant; +use tokio_executor::Enter; /// A handle to a source of time. /// @@ -17,7 +15,7 @@ use std::time::Instant; /// [`Instant::now`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.now #[derive(Default, Clone)] pub struct Clock { - now: Option>, + now: Option>, } thread_local! { @@ -92,7 +90,7 @@ impl timer::Now for Clock { } impl fmt::Debug for Clock { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Clock") .field("now", { if self.now.is_some() { diff --git a/tokio-timer/src/deadline.rs b/tokio-timer/src/deadline.rs index c4c19b8bb..29f0c827e 100644 --- a/tokio-timer/src/deadline.rs +++ b/tokio-timer/src/deadline.rs @@ -1,9 +1,7 @@ #![allow(deprecated)] -use Delay; - +use crate::Delay; use futures::{Async, Future, Poll}; - use std::error; use std::fmt; use std::time::Instant; @@ -31,7 +29,7 @@ enum Kind { Elapsed, /// Timer returned an error. - Timer(::Error), + Timer(crate::Error), } impl Deadline { @@ -128,7 +126,7 @@ impl DeadlineError { /// Creates a new `DeadlineError` representing an error encountered by the /// timer implementation - pub fn timer(err: ::Error) -> DeadlineError { + pub fn timer(err: crate::Error) -> DeadlineError { DeadlineError(Kind::Timer(err)) } @@ -141,7 +139,7 @@ impl DeadlineError { } /// Consumes `self`, returning the error raised by the timer implementation. - pub fn into_timer(self) -> Option<::Error> { + pub fn into_timer(self) -> Option { match self.0 { Kind::Timer(err) => Some(err), _ => None, @@ -162,7 +160,7 @@ impl error::Error for DeadlineError { } impl fmt::Display for DeadlineError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use self::Kind::*; match self.0 { diff --git a/tokio-timer/src/delay.rs b/tokio-timer/src/delay.rs index c48adccd5..941dde7a4 100644 --- a/tokio-timer/src/delay.rs +++ b/tokio-timer/src/delay.rs @@ -1,8 +1,6 @@ -use timer::{HandlePriv, Registration}; -use Error; - +use crate::timer::{HandlePriv, Registration}; +use crate::Error; use futures::{Future, Poll}; - use std::time::{Duration, Instant}; /// A future that completes at a specified instant in time. diff --git a/tokio-timer/src/delay_queue.rs b/tokio-timer/src/delay_queue.rs index 1f4b0a17a..70190e83f 100644 --- a/tokio-timer/src/delay_queue.rs +++ b/tokio-timer/src/delay_queue.rs @@ -4,14 +4,12 @@ //! //! [`DelayQueue`]: struct.DelayQueue.html -use clock::now; -use timer::Handle; -use wheel::{self, Wheel}; -use {Delay, Error}; - -use futures::{Future, Poll, Stream}; +use crate::clock::now; +use crate::timer::Handle; +use crate::wheel::{self, Wheel}; +use crate::{Delay, Error}; +use futures::{try_ready, Future, Poll, Stream}; use slab::Slab; - use std::cmp; use std::marker::PhantomData; use std::time::{Duration, Instant}; @@ -67,16 +65,13 @@ use std::time::{Duration, Instant}; /// /// Using `DelayQueue` to manage cache entries. /// -/// ```rust -/// #[macro_use] -/// extern crate futures; -/// extern crate tokio; -/// # type CacheKey = String; -/// # type Value = String; +/// ```rust,no_run /// use tokio::timer::{delay_queue, DelayQueue, Error}; -/// use futures::{Async, Poll, Stream}; +/// use futures::{try_ready, Async, Poll, Stream}; /// use std::collections::HashMap; /// use std::time::Duration; +/// # type CacheKey = String; +/// # type Value = String; /// /// struct Cache { /// entries: HashMap, @@ -112,7 +107,6 @@ use std::time::{Duration, Instant}; /// Ok(Async::Ready(())) /// } /// } -/// # fn main() {} /// ``` /// /// [`insert`]: #method.insert @@ -301,11 +295,9 @@ impl DelayQueue { /// Basic usage /// /// ```rust - /// # extern crate tokio; /// use tokio::timer::DelayQueue; /// use std::time::{Instant, Duration}; /// - /// # fn main() { /// let mut delay_queue = DelayQueue::new(); /// let key = delay_queue.insert_at( /// "foo", Instant::now() + Duration::from_secs(5)); @@ -313,7 +305,6 @@ impl DelayQueue { /// // Remove the entry /// let item = delay_queue.remove(&key); /// assert_eq!(*item.get_ref(), "foo"); - /// # } /// ``` /// /// [`poll`]: #method.poll @@ -382,18 +373,15 @@ impl DelayQueue { /// Basic usage /// /// ```rust - /// # extern crate tokio; /// use tokio::timer::DelayQueue; /// use std::time::Duration; /// - /// # fn main() { /// 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"); - /// # } /// ``` /// /// [`poll`]: #method.poll @@ -435,21 +423,18 @@ impl DelayQueue { /// Basic usage /// /// ```rust - /// # extern crate tokio; /// use tokio::timer::DelayQueue; /// use std::time::Duration; /// - /// # fn main() { /// 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"); - /// # } /// ``` pub fn remove(&mut self, key: &Key) -> Expired { - use wheel::Stack; + use crate::wheel::Stack; // Special case the `expired` queue if self.slab[key.index].expired { @@ -486,11 +471,9 @@ impl DelayQueue { /// Basic usage /// /// ```rust - /// # extern crate tokio; /// use tokio::timer::DelayQueue; /// use std::time::{Duration, Instant}; /// - /// # fn main() { /// let mut delay_queue = DelayQueue::new(); /// let key = delay_queue.insert("foo", Duration::from_secs(5)); /// @@ -499,7 +482,6 @@ impl DelayQueue { /// delay_queue.reset_at(&key, Instant::now() + Duration::from_secs(10)); /// /// // "foo"is now scheduled to be returned in 10 seconds - /// # } /// ``` pub fn reset_at(&mut self, key: &Key, when: Instant) { self.wheel.remove(&key.index, &mut self.slab); @@ -543,11 +525,9 @@ impl DelayQueue { /// Basic usage /// /// ```rust - /// # extern crate tokio; /// use tokio::timer::DelayQueue; /// use std::time::Duration; /// - /// # fn main() { /// let mut delay_queue = DelayQueue::new(); /// let key = delay_queue.insert("foo", Duration::from_secs(5)); /// @@ -556,7 +536,6 @@ impl DelayQueue { /// delay_queue.reset(&key, Duration::from_secs(10)); /// /// // "foo"is now scheduled to be returned in 10 seconds - /// # } /// ``` pub fn reset(&mut self, key: &Key, timeout: Duration) { self.reset_at(key, now() + timeout); @@ -573,11 +552,9 @@ impl DelayQueue { /// # Examples /// /// ```rust - /// # extern crate tokio; /// use tokio::timer::DelayQueue; /// use std::time::Duration; /// - /// # fn main() { /// let mut delay_queue = DelayQueue::new(); /// /// delay_queue.insert("foo", Duration::from_secs(5)); @@ -587,7 +564,6 @@ impl DelayQueue { /// delay_queue.clear(); /// /// assert!(delay_queue.is_empty()); - /// # } /// ``` pub fn clear(&mut self) { self.slab.clear(); @@ -601,7 +577,8 @@ impl DelayQueue { /// # Examples /// /// ```rust - /// # use tokio_timer::DelayQueue; + /// use tokio_timer::DelayQueue; + /// /// let delay_queue: DelayQueue = DelayQueue::with_capacity(10); /// assert_eq!(delay_queue.capacity(), 10); /// ``` @@ -629,11 +606,14 @@ impl DelayQueue { /// # Examples /// /// ``` - /// # use tokio_timer::DelayQueue; - /// # use std::time::Duration; + /// use tokio_timer::DelayQueue; + /// use std::time::Duration; + /// /// let mut delay_queue = DelayQueue::new(); + /// /// delay_queue.insert("hello", Duration::from_secs(10)); /// delay_queue.reserve(10); + /// /// assert!(delay_queue.capacity() >= 11); /// ``` pub fn reserve(&mut self, additional: usize) { @@ -648,8 +628,9 @@ impl DelayQueue { /// # Examples /// /// ``` - /// # use tokio_timer::DelayQueue; + /// use tokio_timer::DelayQueue; /// use std::time::Duration; + /// /// let mut delay_queue = DelayQueue::new(); /// assert!(delay_queue.is_empty()); /// @@ -679,7 +660,7 @@ impl DelayQueue { try_ready!(delay.poll()); } - let now = ::ms(delay.deadline() - self.start, ::Round::Down); + let now = crate::ms(delay.deadline() - self.start, crate::Round::Down); self.poll = wheel::Poll::new(now); } @@ -702,7 +683,7 @@ impl DelayQueue { let when = if when < self.start { 0 } else { - ::ms(when - self.start, ::Round::Up) + crate::ms(when - self.start, crate::Round::Up) }; cmp::max(when, self.wheel.elapsed()) diff --git a/tokio-timer/src/error.rs b/tokio-timer/src/error.rs index a6136d8b5..968957faa 100644 --- a/tokio-timer/src/error.rs +++ b/tokio-timer/src/error.rs @@ -1,5 +1,4 @@ use self::Kind::*; - use std::error; use std::fmt; @@ -71,7 +70,7 @@ impl error::Error for Error { } impl fmt::Display for Error { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use std::error::Error; self.description().fmt(fmt) } diff --git a/tokio-timer/src/interval.rs b/tokio-timer/src/interval.rs index 019efe6a2..e065bf127 100644 --- a/tokio-timer/src/interval.rs +++ b/tokio-timer/src/interval.rs @@ -1,9 +1,6 @@ -use Delay; - -use clock; - -use futures::{Future, Poll, Stream}; - +use crate::clock; +use crate::Delay; +use futures::{try_ready, Future, Poll, Stream}; use std::time::{Duration, Instant}; /// A stream representing notifications at fixed interval @@ -56,7 +53,7 @@ impl Interval { impl Stream for Interval { type Item = Instant; - type Error = ::Error; + type Error = crate::Error; fn poll(&mut self) -> Poll, Self::Error> { // Wait for the delay to be done diff --git a/tokio-timer/src/lib.rs b/tokio-timer/src/lib.rs index b10692079..3a960240c 100644 --- a/tokio-timer/src/lib.rs +++ b/tokio-timer/src/lib.rs @@ -1,5 +1,7 @@ #![doc(html_root_url = "https://docs.rs/tokio-timer/0.2.10")] -#![deny(missing_docs, warnings, missing_debug_implementations)] +#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! Utilities for tracking time. //! @@ -29,13 +31,6 @@ //! [`Interval`]: struct.Interval.html //! [`Timer`]: timer/struct.Timer.html -extern crate tokio_executor; - -extern crate crossbeam_utils; -#[macro_use] -extern crate futures; -extern crate slab; - pub mod clock; pub mod delay_queue; pub mod throttle; @@ -52,15 +47,15 @@ mod wheel; #[deprecated(since = "0.2.6", note = "use Timeout instead")] #[doc(hidden)] #[allow(deprecated)] -pub use self::deadline::{Deadline, DeadlineError}; -pub use self::delay::Delay; +pub use deadline::{Deadline, DeadlineError}; +pub use delay::Delay; #[doc(inline)] -pub use self::delay_queue::DelayQueue; -pub use self::error::Error; -pub use self::interval::Interval; +pub use delay_queue::DelayQueue; +pub use error::Error; +pub use interval::Interval; #[doc(inline)] -pub use self::timeout::Timeout; -pub use self::timer::{with_default, Timer}; +pub use timeout::Timeout; +pub use timer::{with_default, Timer}; use std::time::{Duration, Instant}; diff --git a/tokio-timer/src/throttle.rs b/tokio-timer/src/throttle.rs index 0ab49aaa5..de71bf7fb 100644 --- a/tokio-timer/src/throttle.rs +++ b/tokio-timer/src/throttle.rs @@ -1,10 +1,8 @@ //! Slow down a stream by enforcing a delay between items. -use {clock, Delay, Error}; - +use crate::{clock, Delay, Error}; use futures::future::Either; -use futures::{Async, Future, Poll, Stream}; - +use futures::{try_ready, Async, Future, Poll, Stream}; use std::{ error::Error as StdError, fmt::{Display, Formatter, Result as FmtResult}, @@ -139,7 +137,7 @@ impl ThrottleError { } impl Display for ThrottleError { - fn fmt(&self, f: &mut Formatter) -> FmtResult { + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { match self.0 { Either::A(ref err) => write!(f, "stream error: {}", err), Either::B(ref err) => write!(f, "timer error: {}", err), @@ -158,7 +156,7 @@ impl StdError for ThrottleError { // FIXME(taiki-e): When the minimum support version of tokio reaches Rust 1.30, // replace this with Error::source. #[allow(deprecated)] - fn cause(&self) -> Option<&StdError> { + fn cause(&self) -> Option<&dyn StdError> { match self.0 { Either::A(ref err) => Some(err), Either::B(ref err) => Some(err), diff --git a/tokio-timer/src/timeout.rs b/tokio-timer/src/timeout.rs index 1c02a6867..e860d3f02 100644 --- a/tokio-timer/src/timeout.rs +++ b/tokio-timer/src/timeout.rs @@ -4,11 +4,9 @@ //! //! [`Timeout`]: struct.Timeout.html -use clock::now; -use Delay; - +use crate::clock::now; +use crate::Delay; use futures::{Async, Future, Poll, Stream}; - use std::error; use std::fmt; use std::time::{Duration, Instant}; @@ -31,8 +29,6 @@ use std::time::{Duration, Instant}; /// example: /// /// ```rust -/// # extern crate futures; -/// # extern crate tokio; /// // import the `timeout` function, usually this is done /// // with `use tokio::prelude::*` /// use tokio::prelude::FutureExt; @@ -40,7 +36,6 @@ use std::time::{Duration, Instant}; /// use futures::sync::mpsc; /// use std::time::Duration; /// -/// # fn main() { /// let (tx, rx) = mpsc::unbounded(); /// # tx.unbounded_send(()).unwrap(); /// # drop(tx); @@ -55,7 +50,6 @@ use std::time::{Duration, Instant}; /// // Wrap the future with a `Timeout` set to expire in 10 milliseconds. /// process.timeout(Duration::from_millis(10)) /// # ).unwrap(); -/// # } /// ``` /// /// # Cancelation @@ -89,7 +83,7 @@ enum Kind { Elapsed, /// Timer returned an error. - Timer(::Error), + Timer(crate::Error), } impl Timeout { @@ -107,14 +101,11 @@ impl Timeout { /// Create a new `Timeout` set to expire in 10 milliseconds. /// /// ```rust - /// # extern crate futures; - /// # extern crate tokio; /// use tokio::timer::Timeout; /// use futures::Future; /// use futures::sync::oneshot; /// use std::time::Duration; /// - /// # fn main() { /// let (tx, rx) = oneshot::channel(); /// # tx.send(()).unwrap(); /// @@ -122,7 +113,6 @@ impl Timeout { /// // Wrap the future with a `Timeout` set to expire in 10 milliseconds. /// Timeout::new(rx, Duration::from_millis(10)) /// # ).unwrap(); - /// # } /// ``` pub fn new(value: T, timeout: Duration) -> Timeout { let delay = Delay::new_timeout(now() + timeout, timeout); @@ -265,7 +255,7 @@ impl Error { /// Creates a new `Error` representing an error encountered by the timer /// implementation - pub fn timer(err: ::Error) -> Error { + pub fn timer(err: crate::Error) -> Error { Error(Kind::Timer(err)) } @@ -278,7 +268,7 @@ impl Error { } /// Consumes `self`, returning the error raised by the timer implementation. - pub fn into_timer(self) -> Option<::Error> { + pub fn into_timer(self) -> Option { match self.0 { Kind::Timer(err) => Some(err), _ => None, @@ -299,7 +289,7 @@ impl error::Error for Error { } impl fmt::Display for Error { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { use self::Kind::*; match self.0 { diff --git a/tokio-timer/src/timer/atomic_stack.rs b/tokio-timer/src/timer/atomic_stack.rs index 4e7d8ed6e..bbc540a25 100644 --- a/tokio-timer/src/timer/atomic_stack.rs +++ b/tokio-timer/src/timer/atomic_stack.rs @@ -1,6 +1,5 @@ use super::Entry; -use Error; - +use crate::Error; use std::ptr; use std::sync::atomic::AtomicPtr; use std::sync::atomic::Ordering::SeqCst; diff --git a/tokio-timer/src/timer/entry.rs b/tokio-timer/src/timer/entry.rs index 40979afae..3ce969a17 100644 --- a/tokio-timer/src/timer/entry.rs +++ b/tokio-timer/src/timer/entry.rs @@ -1,11 +1,9 @@ -use atomic::AtomicU64; -use timer::{HandlePriv, Inner}; -use Error; - +use crate::atomic::AtomicU64; +use crate::timer::{HandlePriv, Inner}; +use crate::Error; use crossbeam_utils::CachePadded; use futures::task::AtomicTask; use futures::Poll; - use std::cell::UnsafeCell; use std::ptr; use std::sync::atomic::AtomicBool; diff --git a/tokio-timer/src/timer/handle.rs b/tokio-timer/src/timer/handle.rs index c9598b9ae..7e8b95c7f 100644 --- a/tokio-timer/src/timer/handle.rs +++ b/tokio-timer/src/timer/handle.rs @@ -1,12 +1,10 @@ -use timer::Inner; -use {Deadline, Delay, Error, Interval, Timeout}; - -use tokio_executor::Enter; - +use crate::timer::Inner; +use crate::{Deadline, Delay, Error, Interval, Timeout}; use std::cell::RefCell; use std::fmt; use std::sync::{Arc, Weak}; use std::time::{Duration, Instant}; +use tokio_executor::Enter; /// Handle to timer instance. /// @@ -190,7 +188,7 @@ impl HandlePriv { } impl fmt::Debug for HandlePriv { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "HandlePriv") } } diff --git a/tokio-timer/src/timer/mod.rs b/tokio-timer/src/timer/mod.rs index 05b0672e6..6b2d7f83c 100644 --- a/tokio-timer/src/timer/mod.rs +++ b/tokio-timer/src/timer/mod.rs @@ -49,18 +49,16 @@ pub use self::handle::{with_default, Handle}; pub use self::now::{Now, SystemNow}; pub(crate) use self::registration::Registration; -use atomic::AtomicU64; -use wheel; -use Error; - -use tokio_executor::park::{Park, ParkThread, Unpark}; - +use crate::atomic::AtomicU64; +use crate::wheel; +use crate::Error; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use std::sync::Arc; use std::time::{Duration, Instant}; use std::usize; use std::{cmp, fmt}; +use tokio_executor::park::{Park, ParkThread, Unpark}; /// Timer implementation that drives [`Delay`], [`Interval`], and [`Timeout`]. /// @@ -162,7 +160,7 @@ pub(crate) struct Inner { process: AtomicStack, /// Unparks the timer thread. - unpark: Box, + unpark: Box, } /// Maximum number of timeouts the system can handle concurrently. @@ -266,7 +264,7 @@ where /// Run timer related logic fn process(&mut self) { - let now = ::ms(self.now.now() - self.inner.start, ::Round::Down); + let now = crate::ms(self.now.now() - self.inner.start, crate::Round::Down); let mut poll = wheel::Poll::new(now); while let Some(entry) = self.wheel.poll(&mut poll, &mut ()) { @@ -317,7 +315,7 @@ where /// /// Returns `None` if the entry was fired. fn add_entry(&mut self, entry: Arc, when: u64) { - use wheel::InsertError; + use crate::wheel::InsertError; entry.set_when_internal(Some(when)); @@ -426,7 +424,7 @@ impl Drop for Timer { // ===== impl Inner ===== impl Inner { - fn new(start: Instant, unpark: Box) -> Inner { + fn new(start: Instant, unpark: Box) -> Inner { Inner { num: AtomicUsize::new(0), elapsed: AtomicU64::new(0), @@ -479,12 +477,12 @@ impl Inner { return 0; } - ::ms(deadline - self.start, ::Round::Up) + crate::ms(deadline - self.start, crate::Round::Up) } } impl fmt::Debug for Inner { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Inner").finish() } } diff --git a/tokio-timer/src/timer/now.rs b/tokio-timer/src/timer/now.rs index 9f23bad71..53754427e 100644 --- a/tokio-timer/src/timer/now.rs +++ b/tokio-timer/src/timer/now.rs @@ -7,4 +7,4 @@ pub trait Now { fn now(&mut self) -> Instant; } -pub use clock::Clock as SystemNow; +pub use crate::clock::Clock as SystemNow; diff --git a/tokio-timer/src/timer/registration.rs b/tokio-timer/src/timer/registration.rs index dad1355dc..ee7e3feb8 100644 --- a/tokio-timer/src/timer/registration.rs +++ b/tokio-timer/src/timer/registration.rs @@ -1,9 +1,7 @@ -use clock::now; -use timer::{Entry, HandlePriv}; -use Error; - +use crate::clock::now; +use crate::timer::{Entry, HandlePriv}; +use crate::Error; use futures::Poll; - use std::sync::Arc; use std::time::{Duration, Instant}; diff --git a/tokio-timer/src/timer/stack.rs b/tokio-timer/src/timer/stack.rs index c63eed971..9309b470b 100644 --- a/tokio-timer/src/timer/stack.rs +++ b/tokio-timer/src/timer/stack.rs @@ -1,6 +1,5 @@ use super::Entry; -use wheel; - +use crate::wheel; use std::ptr; use std::sync::Arc; diff --git a/tokio-timer/src/wheel/level.rs b/tokio-timer/src/wheel/level.rs index 6bbd128e0..868e6a796 100644 --- a/tokio-timer/src/wheel/level.rs +++ b/tokio-timer/src/wheel/level.rs @@ -1,5 +1,4 @@ -use wheel::Stack; - +use crate::wheel::Stack; use std::fmt; /// Wheel for a single level in the timer. This wheel contains 64 slots. @@ -209,7 +208,7 @@ impl Level { } impl fmt::Debug for Level { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Level") .field("occupied", &self.occupied) .finish() diff --git a/tokio-timer/tests/clock.rs b/tokio-timer/tests/clock.rs index d8bcaaebd..d75f3d377 100644 --- a/tokio-timer/tests/clock.rs +++ b/tokio-timer/tests/clock.rs @@ -1,10 +1,9 @@ -extern crate tokio_executor; -extern crate tokio_timer; - -use tokio_timer::clock; -use tokio_timer::clock::*; +#![deny(warnings, rust_2018_idioms)] use std::time::Instant; +use tokio_executor; +use tokio_timer::clock; +use tokio_timer::clock::*; struct ConstNow(Instant); diff --git a/tokio-timer/tests/deadline.rs b/tokio-timer/tests/deadline.rs index 8eec79ae7..712cc5f37 100644 --- a/tokio-timer/tests/deadline.rs +++ b/tokio-timer/tests/deadline.rs @@ -1,16 +1,12 @@ +#![deny(warnings, rust_2018_idioms)] #![allow(deprecated)] -extern crate futures; -extern crate tokio_executor; -extern crate tokio_timer; -#[macro_use] mod support; -use support::*; - -use tokio_timer::*; +use crate::support::*; use futures::sync::oneshot; use futures::{future, Future}; +use tokio_timer::*; #[test] fn simultaneous_deadline_future_completion() { diff --git a/tokio-timer/tests/delay.rs b/tokio-timer/tests/delay.rs index d21106c63..430662600 100644 --- a/tokio-timer/tests/delay.rs +++ b/tokio-timer/tests/delay.rs @@ -1,17 +1,12 @@ -extern crate futures; -extern crate tokio_executor; -extern crate tokio_timer; +#![deny(warnings, rust_2018_idioms)] -#[macro_use] mod support; -use support::*; - -use tokio_timer::timer::Handle; -use tokio_timer::*; +use crate::support::*; use futures::Future; - use std::time::{Duration, Instant}; +use tokio_timer::timer::Handle; +use tokio_timer::*; #[test] fn immediate_delay() { diff --git a/tokio-timer/tests/hammer.rs b/tokio-timer/tests/hammer.rs index 9986a9e65..16e86e1a2 100644 --- a/tokio-timer/tests/hammer.rs +++ b/tokio-timer/tests/hammer.rs @@ -1,21 +1,17 @@ -extern crate futures; -extern crate rand; -extern crate tokio_executor; -extern crate tokio_timer; - -use tokio_executor::park::{Park, Unpark, UnparkThread}; -use tokio_timer::*; +#![deny(warnings, rust_2018_idioms)] use futures::stream::FuturesUnordered; use futures::{Future, Stream}; +use rand; use rand::Rng; - use std::cmp; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use std::sync::{Arc, Barrier}; use std::thread; use std::time::{Duration, Instant}; +use tokio_executor::park::{Park, Unpark, UnparkThread}; +use tokio_timer::*; struct Signal { rem: AtomicUsize, diff --git a/tokio-timer/tests/interval.rs b/tokio-timer/tests/interval.rs index 27828fc83..9b6125852 100644 --- a/tokio-timer/tests/interval.rs +++ b/tokio-timer/tests/interval.rs @@ -1,14 +1,10 @@ -extern crate futures; -extern crate tokio_executor; -extern crate tokio_timer; +#![deny(warnings, rust_2018_idioms)] -#[macro_use] mod support; -use support::*; - -use tokio_timer::*; +use crate::support::*; use futures::Stream; +use tokio_timer::*; #[test] #[should_panic] diff --git a/tokio-timer/tests/queue.rs b/tokio-timer/tests/queue.rs index eeba61041..b11ec6066 100644 --- a/tokio-timer/tests/queue.rs +++ b/tokio-timer/tests/queue.rs @@ -1,16 +1,11 @@ -extern crate futures; -extern crate tokio_executor; -extern crate tokio_mock_task; -extern crate tokio_timer; +#![deny(warnings, rust_2018_idioms)] -#[macro_use] mod support; -use support::*; - -use tokio_mock_task::MockTask; -use tokio_timer::*; +use crate::support::*; use futures::Stream; +use tokio_mock_task::MockTask; +use tokio_timer::*; #[test] fn single_immediate_delay() { @@ -390,7 +385,7 @@ fn reset_first_expiring_item_to_expire_later() { let epoch = time.now(); let foo = queue.insert_at("foo", epoch + ms(200)); - let bar = queue.insert_at("bar", epoch + ms(250)); + let _bar = queue.insert_at("bar", epoch + ms(250)); task.enter(|| { assert_not_ready!(queue); diff --git a/tokio-timer/tests/support/mod.rs b/tokio-timer/tests/support/mod.rs index 244d56b81..f444a534e 100644 --- a/tokio-timer/tests/support/mod.rs +++ b/tokio-timer/tests/support/mod.rs @@ -11,6 +11,7 @@ use std::rc::Rc; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; +#[macro_export] macro_rules! assert_ready { ($f:expr) => {{ use ::futures::Async::*; @@ -33,12 +34,14 @@ macro_rules! assert_ready { }} } +#[macro_export] macro_rules! assert_ready_eq { ($f:expr, $expect:expr) => { assert_eq!($f.poll().unwrap(), ::futures::Async::Ready($expect)); }; } +#[macro_export] macro_rules! assert_not_ready { ($f:expr) => {{ let res = $f.poll().unwrap(); @@ -53,6 +56,7 @@ macro_rules! assert_not_ready { }}; } +#[macro_export] macro_rules! assert_elapsed { ($f:expr) => { assert!($f.poll().unwrap_err().is_elapsed()); diff --git a/tokio-timer/tests/throttle.rs b/tokio-timer/tests/throttle.rs index 253309c98..96c384c75 100644 --- a/tokio-timer/tests/throttle.rs +++ b/tokio-timer/tests/throttle.rs @@ -1,10 +1,7 @@ -extern crate futures; -extern crate tokio_executor; -extern crate tokio_timer; +#![deny(warnings, rust_2018_idioms)] -#[macro_use] mod support; -use support::*; +use crate::support::*; use futures::{prelude::*, sync::mpsc}; use tokio_timer::throttle::Throttle; diff --git a/tokio-timer/tests/timeout.rs b/tokio-timer/tests/timeout.rs index 8e10776ae..9e9a808af 100644 --- a/tokio-timer/tests/timeout.rs +++ b/tokio-timer/tests/timeout.rs @@ -1,15 +1,11 @@ -extern crate futures; -extern crate tokio_executor; -extern crate tokio_timer; +#![deny(warnings, rust_2018_idioms)] -#[macro_use] mod support; -use support::*; - -use tokio_timer::*; +use crate::support::*; use futures::sync::{mpsc, oneshot}; use futures::{future, Future, Stream}; +use tokio_timer::*; #[test] fn simultaneous_deadline_future_completion() { diff --git a/tokio-tls/Cargo.toml b/tokio-tls/Cargo.toml index 3d48213d5..f026a0bf6 100644 --- a/tokio-tls/Cargo.toml +++ b/tokio-tls/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-tls" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.2.x" git tag. -version = "0.2.1" +# - Create "v0.3.x" git tag. +version = "0.3.0" +edition = "2018" authors = ["Carl Lerche "] license = "MIT" repository = "https://github.com/tokio-rs/tokio" @@ -19,6 +20,7 @@ An implementation of TLS/SSL streams for Tokio giving an implementation of TLS for nonblocking I/O streams. """ categories = ["asynchronous", "network-programming"] +publish = false [badges] travis-ci = { repository = "tokio-rs/tokio-tls" } @@ -26,10 +28,10 @@ travis-ci = { repository = "tokio-rs/tokio-tls" } [dependencies] futures = "0.1.23" native-tls = "0.2" -tokio-io = "0.1.7" +tokio-io = { version = "0.2.0", path = "../tokio-io" } [dev-dependencies] -tokio = "0.1" +tokio = { version = "0.2.0", path = "../tokio" } cfg-if = "0.1" env_logger = { version = "0.5", default-features = false } diff --git a/tokio-tls/README.md b/tokio-tls/README.md index c82a78ca8..f033ae1bf 100644 --- a/tokio-tls/README.md +++ b/tokio-tls/README.md @@ -20,9 +20,6 @@ tokio-tls = "0.2" Next, add this to your crate: ```rust -extern crate native_tls; -extern crate tokio_tls; - use tokio_tls::{TlsConnector, TlsAcceptor}; ``` diff --git a/tokio-tls/examples/download-rust-lang.rs b/tokio-tls/examples/download-rust-lang.rs index 9d23dc78f..08e463bf1 100644 --- a/tokio-tls/examples/download-rust-lang.rs +++ b/tokio-tls/examples/download-rust-lang.rs @@ -1,18 +1,15 @@ -extern crate futures; -extern crate native_tls; -extern crate tokio; -extern crate tokio_io; -extern crate tokio_tls; - -use std::io; -use std::net::ToSocketAddrs; +#![deny(warnings, rust_2018_idioms)] use futures::Future; use native_tls::TlsConnector; +use std::io; +use std::net::ToSocketAddrs; use tokio::net::TcpStream; use tokio::runtime::Runtime; +use tokio_io; +use tokio_tls; -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { let mut runtime = Runtime::new()?; let addr = "www.rust-lang.org:443" .to_socket_addrs()? diff --git a/tokio-tls/examples/echo.rs b/tokio-tls/examples/echo.rs index c39d5873b..7622eae04 100644 --- a/tokio-tls/examples/echo.rs +++ b/tokio-tls/examples/echo.rs @@ -1,14 +1,15 @@ -// A tiny async TLS echo server with Tokio -extern crate native_tls; -extern crate tokio; -extern crate tokio_tls; +#![deny(warnings, rust_2018_idioms)] +// A tiny async TLS echo server with Tokio +use native_tls; use native_tls::Identity; +use tokio; use tokio::io; use tokio::net::TcpListener; use tokio::prelude::*; +use tokio_tls; -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { // Bind the server's socket let addr = "127.0.0.1:12345".parse()?; let tcp = TcpListener::bind(&addr)?; diff --git a/tokio-tls/src/lib.rs b/tokio-tls/src/lib.rs index 66bc39648..21932799e 100644 --- a/tokio-tls/src/lib.rs +++ b/tokio-tls/src/lib.rs @@ -1,5 +1,7 @@ -#![deny(missing_docs)] #![doc(html_root_url = "https://docs.rs/tokio-tls/0.2.1")] +#![deny(rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! Async TLS streams //! @@ -18,16 +20,10 @@ //! built. Configuration of TLS parameters is still primarily done through the //! `native-tls` crate. -extern crate futures; -extern crate native_tls; -#[macro_use] -extern crate tokio_io; - -use std::io::{self, Read, Write}; - use futures::{Async, Future, Poll}; use native_tls::{Error, HandshakeError}; -use tokio_io::{AsyncRead, AsyncWrite}; +use std::io::{self, Read, Write}; +use tokio_io::{try_nb, AsyncRead, AsyncWrite}; /// A wrapper around an underlying raw stream which implements the TLS or SSL /// protocol. diff --git a/tokio-tls/tests/bad.rs b/tokio-tls/tests/bad.rs index 8b010a2a6..e72b2d23a 100644 --- a/tokio-tls/tests/bad.rs +++ b/tokio-tls/tests/bad.rs @@ -1,19 +1,14 @@ -extern crate env_logger; -extern crate futures; -extern crate native_tls; -extern crate tokio; -extern crate tokio_tls; - -#[macro_use] -extern crate cfg_if; - -use std::io::{self, Error}; -use std::net::ToSocketAddrs; +#![deny(warnings, rust_2018_idioms)] +use cfg_if::cfg_if; +use env_logger; use futures::Future; use native_tls::TlsConnector; +use std::io::{self, Error}; +use std::net::ToSocketAddrs; use tokio::net::TcpStream; use tokio::runtime::Runtime; +use tokio_tls; macro_rules! t { ($e:expr) => { @@ -50,8 +45,6 @@ cfg_if! { all(not(target_os = "macos"), not(target_os = "windows"), not(target_os = "ios"))))] { - extern crate openssl; - fn verify_failed(err: &Error) { assert!(format!("{}", err).contains("certificate verify failed")) } @@ -66,10 +59,10 @@ cfg_if! { assert!(format!("{}", err).contains("was not trusted.")) } - use assert_invalid_cert_chain as assert_expired_error; - use assert_invalid_cert_chain as assert_wrong_host; - use assert_invalid_cert_chain as assert_self_signed; - use assert_invalid_cert_chain as assert_untrusted_root; + use crate::assert_invalid_cert_chain as assert_expired_error; + use crate::assert_invalid_cert_chain as assert_wrong_host; + use crate::assert_invalid_cert_chain as assert_self_signed; + use crate::assert_invalid_cert_chain as assert_untrusted_root; } else { fn assert_expired_error(err: &Error) { let s = err.to_string(); diff --git a/tokio-tls/tests/google.rs b/tokio-tls/tests/google.rs index aa4fc0f09..15346d4c8 100644 --- a/tokio-tls/tests/google.rs +++ b/tokio-tls/tests/google.rs @@ -1,21 +1,16 @@ -extern crate env_logger; -extern crate futures; -extern crate native_tls; -extern crate tokio; -extern crate tokio_io; -extern crate tokio_tls; - -#[macro_use] -extern crate cfg_if; +#![deny(warnings, rust_2018_idioms)] +use cfg_if::cfg_if; +use env_logger; +use futures::Future; +use native_tls; +use native_tls::TlsConnector; use std::io; use std::net::ToSocketAddrs; - -use futures::Future; -use native_tls::TlsConnector; use tokio::net::TcpStream; use tokio::runtime::Runtime; use tokio_io::io::{flush, read_to_end, write_all}; +use tokio_tls; macro_rules! t { ($e:expr) => { @@ -36,8 +31,6 @@ cfg_if! { all(not(target_os = "macos"), not(target_os = "windows"), not(target_os = "ios"))))] { - extern crate openssl; - fn assert_bad_hostname_error(err: &io::Error) { let err = err.get_ref().unwrap(); let err = err.downcast_ref::().unwrap(); @@ -92,7 +85,7 @@ fn fetch_google() { assert!(data.starts_with(b"HTTP/1.0 ")); let data = String::from_utf8_lossy(&data); - let data = data.trim_right(); + let data = data.trim_end(); assert!(data.ends_with("") || data.ends_with("")); } diff --git a/tokio-tls/tests/smoke.rs b/tokio-tls/tests/smoke.rs index 33a4a3a38..18d5dde8c 100644 --- a/tokio-tls/tests/smoke.rs +++ b/tokio-tls/tests/smoke.rs @@ -1,23 +1,18 @@ -extern crate env_logger; -extern crate futures; -extern crate native_tls; -extern crate tokio; -extern crate tokio_io; -extern crate tokio_tls; - -#[macro_use] -extern crate cfg_if; - -use std::io::{self, Read, Write}; -use std::process::Command; +#![deny(warnings, rust_2018_idioms)] +use cfg_if::cfg_if; +use env_logger; use futures::stream::Stream; use futures::{Future, Poll}; +use native_tls; use native_tls::{Identity, TlsAcceptor, TlsConnector}; +use std::io::{self, Read, Write}; +use std::process::Command; use tokio::net::{TcpListener, TcpStream}; use tokio::runtime::Runtime; use tokio_io::io::{copy, read_to_end, shutdown}; use tokio_io::{AsyncRead, AsyncWrite}; +use tokio_tls; macro_rules! t { ($e:expr) => { @@ -130,9 +125,8 @@ fn openssl_keys() -> &'static Keys { cfg_if! { if #[cfg(feature = "rustls")] { - extern crate webpki; - extern crate untrusted; - + use webpki; + use untrusted; use std::env; use std::fs::File; use std::process::Command; @@ -230,8 +224,6 @@ cfg_if! { all(not(target_os = "macos"), not(target_os = "windows"), not(target_os = "ios"))))] { - extern crate openssl; - use std::fs::File; use std::env; use std::sync::{Once, ONCE_INIT}; @@ -250,8 +242,6 @@ cfg_if! { (t!(srv.build()).into(), t!(client.build()).into()) } } else if #[cfg(any(target_os = "macos", target_os = "ios"))] { - extern crate security_framework; - use std::env; use std::fs::File; use std::sync::{Once, ONCE_INIT}; @@ -269,8 +259,8 @@ cfg_if! { (t!(srv.build()).into(), t!(client.build()).into()) } } else { - extern crate schannel; - extern crate winapi; + use schannel; + use winapi; use std::env; use std::fs::File; diff --git a/tokio-udp/Cargo.toml b/tokio-udp/Cargo.toml index c7a66f918..2414ca13e 100644 --- a/tokio-udp/Cargo.toml +++ b/tokio-udp/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-udp" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.1.x" git tag. -version = "0.1.3" +# - Create "v0.2.x" git tag. +version = "0.2.0" +edition = "2018" authors = ["Carl Lerche "] license = "MIT" documentation = "https://docs.rs/tokio-udp/0.1.3/tokio_udp" @@ -18,11 +19,12 @@ description = """ UDP bindings for tokio. """ categories = ["asynchronous"] +publish = false [dependencies] -tokio-codec = "0.1.0" -tokio-io = "0.1.7" -tokio-reactor = "0.1.1" +tokio-codec = { version = "0.2.0", path = "../tokio-codec" } +tokio-io = { version = "0.2.0", path = "../tokio-io" } +tokio-reactor = { version = "0.2.0", path = "../tokio-reactor" } bytes = "0.4" mio = "0.6.14" log = "0.4" diff --git a/tokio-udp/src/frame.rs b/tokio-udp/src/frame.rs index b7ae49010..70111594b 100644 --- a/tokio-udp/src/frame.rs +++ b/tokio-udp/src/frame.rs @@ -1,11 +1,9 @@ +use super::UdpSocket; +use bytes::{BufMut, BytesMut}; +use futures::{try_ready, Async, AsyncSink, Poll, Sink, StartSend, Stream}; +use log::trace; use std::io; use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; - -use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; - -use super::UdpSocket; - -use bytes::{BufMut, BytesMut}; use tokio_codec::{Decoder, Encoder}; /// A unified `Stream` and `Sink` interface to an underlying `UdpSocket`, using diff --git a/tokio-udp/src/lib.rs b/tokio-udp/src/lib.rs index aed9df59e..5202e6def 100644 --- a/tokio-udp/src/lib.rs +++ b/tokio-udp/src/lib.rs @@ -1,5 +1,7 @@ #![doc(html_root_url = "https://docs.rs/tokio-tcp/0.1.3")] -#![deny(missing_docs, warnings, missing_debug_implementations)] +#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! UDP bindings for `tokio`. //! @@ -19,16 +21,6 @@ //! [`UdpFramed`]: struct.UdpFramed.html //! [`framed`]: struct.UdpSocket.html#method.framed -extern crate bytes; -#[macro_use] -extern crate futures; -extern crate mio; -#[macro_use] -extern crate log; -extern crate tokio_codec; -extern crate tokio_io; -extern crate tokio_reactor; - mod frame; mod recv_dgram; mod send_dgram; diff --git a/tokio-udp/src/recv_dgram.rs b/tokio-udp/src/recv_dgram.rs index 5ed63f929..962f13d3f 100644 --- a/tokio-udp/src/recv_dgram.rs +++ b/tokio-udp/src/recv_dgram.rs @@ -1,10 +1,8 @@ use super::socket::UdpSocket; - +use futures::{try_ready, Async, Future, Poll}; use std::io; use std::net::SocketAddr; -use futures::{Async, Future, Poll}; - /// A future used to receive a datagram from a UDP socket. /// /// This is created by the `UdpSocket::recv_dgram` method. @@ -47,13 +45,15 @@ impl RecvDgram { /// Consume the `RecvDgram`, returning the socket and buffer. /// + /// # Panics + /// + /// If called after the future has completed. + /// + /// # Examples + /// /// ``` - /// # extern crate tokio_udp; - /// /// use tokio_udp::UdpSocket; /// - /// # pub fn main() { - /// /// let socket = UdpSocket::bind(&([127, 0, 0, 1], 0).into()).unwrap(); /// let mut buffer = vec![0; 4096]; /// @@ -65,12 +65,7 @@ impl RecvDgram { /// /// let socket = parts.socket; // extract the socket /// let buffer = parts.buffer; // extract the buffer - /// - /// # } /// ``` - /// # Panics - /// - /// If called after the future has completed. pub fn into_parts(mut self) -> Parts { let state = self .state diff --git a/tokio-udp/src/send_dgram.rs b/tokio-udp/src/send_dgram.rs index ccfa1236f..eae8b8962 100644 --- a/tokio-udp/src/send_dgram.rs +++ b/tokio-udp/src/send_dgram.rs @@ -1,10 +1,8 @@ use super::socket::UdpSocket; - +use futures::{try_ready, Async, Future, Poll}; use std::io; use std::net::SocketAddr; -use futures::{Async, Future, Poll}; - /// A future used to write the entire contents of some data to a UDP socket. /// /// This is created by the `UdpSocket::send_dgram` method. diff --git a/tokio-udp/src/socket.rs b/tokio-udp/src/socket.rs index e3d3b6863..765018da4 100644 --- a/tokio-udp/src/socket.rs +++ b/tokio-udp/src/socket.rs @@ -1,12 +1,9 @@ use super::{RecvDgram, SendDgram}; - +use futures::{try_ready, Async, Poll}; +use mio; use std::fmt; use std::io; use std::net::{self, Ipv4Addr, Ipv6Addr, SocketAddr}; - -use futures::{Async, Poll}; -use mio; - use tokio_reactor::{Handle, PollEvented}; /// An I/O object representing a UDP socket. @@ -422,7 +419,7 @@ impl UdpSocket { } impl fmt::Debug for UdpSocket { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.io.get_ref().fmt(f) } } diff --git a/tokio-udp/tests/udp.rs b/tokio-udp/tests/udp.rs index aadd15ca8..ed25a4d1c 100644 --- a/tokio-udp/tests/udp.rs +++ b/tokio-udp/tests/udp.rs @@ -1,18 +1,12 @@ -extern crate futures; -extern crate tokio_codec; -extern crate tokio_udp; -#[macro_use] -extern crate tokio_io; -extern crate bytes; -extern crate env_logger; - -use std::io; -use std::net::SocketAddr; - -use futures::{Future, Poll, Sink, Stream}; +#![deny(warnings, rust_2018_idioms)] use bytes::{BufMut, BytesMut}; +use env_logger; +use futures::{Future, Poll, Sink, Stream}; +use std::io; +use std::net::SocketAddr; use tokio_codec::{Decoder, Encoder}; +use tokio_io::try_nb; use tokio_udp::{UdpFramed, UdpSocket}; macro_rules! t { @@ -56,7 +50,7 @@ fn send_and_recv() { } trait SendFn { - fn send(&self, &mut UdpSocket, &[u8], &SocketAddr) -> Result; + fn send(&self, _: &mut UdpSocket, _: &[u8], _: &SocketAddr) -> Result; } #[derive(Debug, Clone)] @@ -69,6 +63,7 @@ impl SendFn for SendTo { buf: &[u8], addr: &SocketAddr, ) -> Result { + #[allow(deprecated)] socket.send_to(buf, addr) } } @@ -84,6 +79,7 @@ impl SendFn for Send { addr: &SocketAddr, ) -> Result { socket.connect(addr).expect("could not connect"); + #[allow(deprecated)] socket.send(buf) } } @@ -122,7 +118,7 @@ impl Future for SendMessage { } trait RecvFn { - fn recv(&self, &mut UdpSocket, &mut [u8], &SocketAddr) -> Result; + fn recv(&self, _: &mut UdpSocket, _: &mut [u8], _: &SocketAddr) -> Result; } #[derive(Debug, Clone)] @@ -135,6 +131,7 @@ impl RecvFn for RecvFrom { buf: &mut [u8], expected_addr: &SocketAddr, ) -> Result { + #[allow(deprecated)] socket.recv_from(buf).map(|(s, addr)| { assert_eq!(addr, *expected_addr); s @@ -152,6 +149,7 @@ impl RecvFn for Recv { buf: &mut [u8], _: &SocketAddr, ) -> Result { + #[allow(deprecated)] socket.recv(buf) } } diff --git a/tokio-uds/Cargo.toml b/tokio-uds/Cargo.toml index a884f1bca..4241e9546 100644 --- a/tokio-uds/Cargo.toml +++ b/tokio-uds/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio-uds" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.2.x" git tag. -version = "0.2.5" +# - Create "v0.3.x" git tag. +version = "0.3.0" +edition = "2018" authors = ["Carl Lerche "] license = "MIT" repository = "https://github.com/tokio-rs/tokio" @@ -18,6 +19,7 @@ description = """ Unix Domain sockets for Tokio """ categories = ["asynchronous"] +publish = false [dependencies] bytes = "0.4.8" @@ -27,10 +29,10 @@ libc = "0.2.42" log = "0.4.2" mio = "0.6.14" mio-uds = "0.6.5" -tokio-codec = "0.1.0" -tokio-reactor = "0.1.1" -tokio-io = "0.1.6" +tokio-codec = { version = "0.2.0", path = "../tokio-codec" } +tokio-reactor = { version = "0.2.0", path = "../tokio-reactor" } +tokio-io = { version = "0.2.0", path = "../tokio-io" } [dev-dependencies] -tokio = "0.1.6" +tokio = { version = "0.2.0", path = "../tokio" } tempfile = "3" diff --git a/tokio-uds/src/datagram.rs b/tokio-uds/src/datagram.rs index da3f751a9..040f9c641 100644 --- a/tokio-uds/src/datagram.rs +++ b/tokio-uds/src/datagram.rs @@ -1,17 +1,14 @@ -use {RecvDgram, SendDgram}; - -use tokio_reactor::{Handle, PollEvented}; - -use futures::{Async, Poll}; +use crate::{RecvDgram, SendDgram}; +use futures::{try_ready, Async, Poll}; use mio::Ready; use mio_uds; - use std::fmt; use std::io; use std::net::Shutdown; use std::os::unix::io::{AsRawFd, RawFd}; use std::os::unix::net::{self, SocketAddr}; use std::path::Path; +use tokio_reactor::{Handle, PollEvented}; /// An I/O object representing a Unix datagram socket. pub struct UnixDatagram { @@ -197,7 +194,7 @@ impl UnixDatagram { } impl fmt::Debug for UnixDatagram { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.io.get_ref().fmt(f) } } diff --git a/tokio-uds/src/frame.rs b/tokio-uds/src/frame.rs index 6a4174077..66b4fff2c 100644 --- a/tokio-uds/src/frame.rs +++ b/tokio-uds/src/frame.rs @@ -1,12 +1,10 @@ +use super::UnixDatagram; +use bytes::{BufMut, BytesMut}; +use futures::{try_ready, Async, AsyncSink, Poll, Sink, StartSend, Stream}; +use log::trace; use std::io; use std::os::unix::net::SocketAddr; use std::path::Path; - -use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; - -use super::UnixDatagram; - -use bytes::{BufMut, BytesMut}; use tokio_codec::{Decoder, Encoder}; /// A unified `Stream` and `Sink` interface to an underlying `UnixDatagram`, using diff --git a/tokio-uds/src/incoming.rs b/tokio-uds/src/incoming.rs index 472fcf9bf..c904a926d 100644 --- a/tokio-uds/src/incoming.rs +++ b/tokio-uds/src/incoming.rs @@ -1,7 +1,5 @@ -use {UnixListener, UnixStream}; - -use futures::{Poll, Stream}; - +use crate::{UnixListener, UnixStream}; +use futures::{try_ready, Poll, Stream}; use std::io; /// Stream of listeners diff --git a/tokio-uds/src/lib.rs b/tokio-uds/src/lib.rs index feacf2f97..55a35e690 100644 --- a/tokio-uds/src/lib.rs +++ b/tokio-uds/src/lib.rs @@ -1,24 +1,13 @@ #![cfg(unix)] #![doc(html_root_url = "https://docs.rs/tokio-uds/0.2.5")] -#![deny(missing_docs, warnings, missing_debug_implementations)] +#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! Unix Domain Sockets for Tokio. //! //! This crate provides APIs for using Unix Domain Sockets with Tokio. -extern crate bytes; -#[macro_use] -extern crate futures; -extern crate iovec; -extern crate libc; -#[macro_use] -extern crate log; -extern crate mio; -extern crate mio_uds; -extern crate tokio_codec; -extern crate tokio_io; -extern crate tokio_reactor; - mod datagram; mod frame; mod incoming; @@ -28,11 +17,11 @@ mod send_dgram; mod stream; mod ucred; -pub use datagram::UnixDatagram; -pub use frame::UnixDatagramFramed; -pub use incoming::Incoming; -pub use listener::UnixListener; -pub use recv_dgram::RecvDgram; -pub use send_dgram::SendDgram; -pub use stream::{ConnectFuture, UnixStream}; -pub use ucred::UCred; +pub use crate::datagram::UnixDatagram; +pub use crate::frame::UnixDatagramFramed; +pub use crate::incoming::Incoming; +pub use crate::listener::UnixListener; +pub use crate::recv_dgram::RecvDgram; +pub use crate::send_dgram::SendDgram; +pub use crate::stream::{ConnectFuture, UnixStream}; +pub use crate::ucred::UCred; diff --git a/tokio-uds/src/listener.rs b/tokio-uds/src/listener.rs index c63b4a843..865197ec4 100644 --- a/tokio-uds/src/listener.rs +++ b/tokio-uds/src/listener.rs @@ -1,16 +1,13 @@ -use {Incoming, UnixStream}; - -use tokio_reactor::{Handle, PollEvented}; - -use futures::{Async, Poll}; +use crate::{Incoming, UnixStream}; +use futures::{try_ready, Async, Poll}; use mio::Ready; use mio_uds; - use std::fmt; use std::io; use std::os::unix::io::{AsRawFd, RawFd}; use std::os::unix::net::{self, SocketAddr}; use std::path::Path; +use tokio_reactor::{Handle, PollEvented}; /// A Unix socket which can accept connections from other Unix sockets. pub struct UnixListener { @@ -134,7 +131,7 @@ impl UnixListener { } impl fmt::Debug for UnixListener { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.io.get_ref().fmt(f) } } diff --git a/tokio-uds/src/recv_dgram.rs b/tokio-uds/src/recv_dgram.rs index 8bb616801..0e03f26ab 100644 --- a/tokio-uds/src/recv_dgram.rs +++ b/tokio-uds/src/recv_dgram.rs @@ -1,7 +1,5 @@ -use UnixDatagram; - -use futures::{Async, Future, Poll}; - +use crate::UnixDatagram; +use futures::{try_ready, Async, Future, Poll}; use std::io; use std::mem; diff --git a/tokio-uds/src/send_dgram.rs b/tokio-uds/src/send_dgram.rs index d598646a4..69004cf5c 100644 --- a/tokio-uds/src/send_dgram.rs +++ b/tokio-uds/src/send_dgram.rs @@ -1,7 +1,5 @@ -use UnixDatagram; - -use futures::{Async, Future, Poll}; - +use crate::UnixDatagram; +use futures::{try_ready, Async, Future, Poll}; use std::io; use std::mem; use std::path::Path; diff --git a/tokio-uds/src/stream.rs b/tokio-uds/src/stream.rs index dfb0724d4..b14b0e07e 100644 --- a/tokio-uds/src/stream.rs +++ b/tokio-uds/src/stream.rs @@ -1,21 +1,18 @@ -use ucred::{self, UCred}; - -use tokio_io::{AsyncRead, AsyncWrite}; -use tokio_reactor::{Handle, PollEvented}; - +use crate::ucred::{self, UCred}; use bytes::{Buf, BufMut}; use futures::{Async, Future, Poll}; use iovec::{self, IoVec}; use libc; use mio::Ready; use mio_uds; - use std::fmt; use std::io::{self, Read, Write}; use std::net::Shutdown; use std::os::unix::io::{AsRawFd, RawFd}; use std::os::unix::net::{self, SocketAddr}; use std::path::Path; +use tokio_io::{AsyncRead, AsyncWrite}; +use tokio_reactor::{Handle, PollEvented}; /// A structure representing a connected Unix socket. /// @@ -238,7 +235,7 @@ impl<'a> AsyncWrite for &'a UnixStream { } impl fmt::Debug for UnixStream { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.io.get_ref().fmt(f) } } diff --git a/tokio-uds/src/ucred.rs b/tokio-uds/src/ucred.rs index 92843e895..0e74f8370 100644 --- a/tokio-uds/src/ucred.rs +++ b/tokio-uds/src/ucred.rs @@ -27,14 +27,15 @@ pub use self::impl_solaris::get_peer_cred; #[cfg(any(target_os = "linux", target_os = "android"))] pub mod impl_linux { + use crate::UnixStream; use libc::{c_void, getsockopt, socklen_t, SOL_SOCKET, SO_PEERCRED}; - use std::os::unix::io::AsRawFd; use std::{io, mem}; - use UnixStream; use libc::ucred; pub fn get_peer_cred(sock: &UnixStream) -> io::Result { + use std::os::unix::io::AsRawFd; + unsafe { let raw_fd = sock.as_raw_fd(); @@ -80,10 +81,10 @@ pub mod impl_linux { target_os = "openbsd" ))] pub mod impl_macos { + use crate::UnixStream; use libc::getpeereid; use std::os::unix::io::AsRawFd; use std::{io, mem}; - use UnixStream; pub fn get_peer_cred(sock: &UnixStream) -> io::Result { unsafe { @@ -149,9 +150,9 @@ pub mod impl_solaris { #[cfg(not(target_os = "dragonfly"))] #[cfg(test)] mod test { + use crate::UnixStream; use libc::getegid; use libc::geteuid; - use UnixStream; #[test] #[cfg_attr( diff --git a/tokio-uds/tests/datagram.rs b/tokio-uds/tests/datagram.rs index d7d6b587c..9ae465107 100644 --- a/tokio-uds/tests/datagram.rs +++ b/tokio-uds/tests/datagram.rs @@ -1,24 +1,14 @@ #![cfg(unix)] - -extern crate bytes; -extern crate futures; -extern crate tempfile; -extern crate tokio; -extern crate tokio_codec; -extern crate tokio_uds; - -use tokio_uds::*; - -use std::str; +#![deny(warnings, rust_2018_idioms)] use bytes::BytesMut; - +use futures::{Future, Sink, Stream}; +use std::str; +use tempfile; use tokio::io; use tokio::runtime::current_thread::Runtime; - use tokio_codec::{Decoder, Encoder}; - -use futures::{Future, Sink, Stream}; +use tokio_uds::*; struct StringDatagramCodec; diff --git a/tokio-uds/tests/stream.rs b/tokio-uds/tests/stream.rs index c9de684fb..216ae80a2 100644 --- a/tokio-uds/tests/stream.rs +++ b/tokio-uds/tests/stream.rs @@ -1,19 +1,12 @@ #![cfg(unix)] - -extern crate futures; -extern crate tokio; -extern crate tokio_uds; - -extern crate tempfile; - -use tokio_uds::*; - -use tokio::io; -use tokio::runtime::current_thread::Runtime; +#![deny(warnings, rust_2018_idioms)] use futures::sync::oneshot; use futures::{Future, Stream}; use tempfile::Builder; +use tokio::io; +use tokio::runtime::current_thread::Runtime; +use tokio_uds::*; macro_rules! t { ($e:expr) => { diff --git a/tokio/Cargo.toml b/tokio/Cargo.toml index 085e4d1ae..54d8e0243 100644 --- a/tokio/Cargo.toml +++ b/tokio/Cargo.toml @@ -7,8 +7,9 @@ name = "tokio" # - Cargo.toml # - README.md # - Update CHANGELOG.md. -# - Create "v0.1.x" git tag. -version = "0.1.19" +# - Create "v0.2.x" git tag. +version = "0.2.0" +edition = "2018" authors = ["Carl Lerche "] license = "MIT" readme = "README.md" @@ -21,6 +22,7 @@ backed applications. """ categories = ["asynchronous", "network-programming"] keywords = ["io", "async", "non-blocking", "futures"] +publish = false [features] default = [ @@ -69,25 +71,25 @@ futures = "0.1.20" # Everything else is optional... bytes = { version = "0.4", optional = true } num_cpus = { version = "1.8.0", optional = true } -tokio-codec = { version = "0.1.0", optional = true } -tokio-current-thread = { version = "0.1.6", optional = true } -tokio-fs = { version = "0.1.6", optional = true } -tokio-io = { version = "0.1.6", optional = true } -tokio-executor = { version = "0.1.7", optional = true } +tokio-codec = { version = "0.2.0", optional = true, path = "../tokio-codec" } +tokio-current-thread = { version = "0.2.0", optional = true, path = "../tokio-current-thread" } +tokio-fs = { version = "0.2.0", optional = true, path = "../tokio-fs" } +tokio-io = { version = "0.2.0", optional = true, path = "../tokio-io" } +tokio-executor = { version = "0.2.0", optional = true, path = "../tokio-executor" } tokio-macros = { version = "0.1.0", optional = true, path = "../tokio-macros" } -tokio-reactor = { version = "0.1.1", optional = true } -tokio-sync = { version = "0.1.5", optional = true } -tokio-threadpool = { version = "0.1.14", optional = true } -tokio-tcp = { version = "0.1.0", optional = true } -tokio-udp = { version = "0.1.0", optional = true } -tokio-timer = { version = "0.2.8", optional = true } +tokio-reactor = { version = "0.2.0", optional = true, path = "../tokio-reactor" } +tokio-sync = { version = "0.2.0", optional = true, path = "../tokio-sync" } +tokio-threadpool = { version = "0.2.0", optional = true, path = "../tokio-threadpool" } +tokio-tcp = { version = "0.2.0", optional = true, path = "../tokio-tcp" } +tokio-udp = { version = "0.2.0", optional = true, path = "../tokio-udp" } +tokio-timer = { version = "0.3.0", optional = true, path = "../tokio-timer" } tokio-trace-core = { version = "0.1", optional = true } # Needed until `reactor` is removed from `tokio`. mio = { version = "0.6.14", optional = true } # Needed for async/await preview support -tokio-futures = { version = "0.1.0", optional = true, path = "../tokio-futures" } +tokio-futures = { version = "0.2.0", optional = true, path = "../tokio-futures" } [target.'cfg(unix)'.dependencies] tokio-uds = { version = "0.2.1", optional = true } @@ -100,7 +102,6 @@ http = "0.1" httparse = "1.0" libc = "0.2" num_cpus = "1.0" -serde = "1.0" -serde_derive = "1.0" +serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" time = "0.1" diff --git a/tokio/README.md b/tokio/README.md index 3d632f0e8..6ff9f091d 100644 --- a/tokio/README.md +++ b/tokio/README.md @@ -54,8 +54,6 @@ an asynchronous application. A basic TCP echo server with Tokio: ```rust -extern crate tokio; - use tokio::prelude::*; use tokio::io::copy; use tokio::net::TcpListener; diff --git a/benches/latency.rs b/tokio/benches/latency.rs similarity index 97% rename from benches/latency.rs rename to tokio/benches/latency.rs index d9ace03a4..1ea3574d8 100644 --- a/benches/latency.rs +++ b/tokio/benches/latency.rs @@ -1,10 +1,7 @@ #![feature(test)] -#![deny(warnings)] +#![deny(warnings, rust_2018_idioms)] extern crate test; -#[macro_use] -extern crate futures; -extern crate tokio; use std::io; use std::net::SocketAddr; @@ -12,6 +9,7 @@ use std::thread; use futures::sync::mpsc; use futures::sync::oneshot; +use futures::try_ready; use futures::{Future, Poll, Sink, Stream}; use test::Bencher; use tokio::net::UdpSocket; diff --git a/benches/mio-ops.rs b/tokio/benches/mio-ops.rs similarity index 97% rename from benches/mio-ops.rs rename to tokio/benches/mio-ops.rs index be4db7f79..dffb7e9a7 100644 --- a/benches/mio-ops.rs +++ b/tokio/benches/mio-ops.rs @@ -1,9 +1,8 @@ // Measure cost of different operations // to get a sense of performance tradeoffs #![feature(test)] -#![deny(warnings)] +#![deny(warnings, rust_2018_idioms)] -extern crate mio; extern crate test; use test::Bencher; diff --git a/benches/tcp.rs b/tokio/benches/tcp.rs similarity index 97% rename from benches/tcp.rs rename to tokio/benches/tcp.rs index 1872790d9..124be3695 100644 --- a/benches/tcp.rs +++ b/tokio/benches/tcp.rs @@ -1,11 +1,5 @@ #![feature(test)] -#![deny(warnings)] - -extern crate futures; -extern crate tokio; - -#[macro_use] -extern crate tokio_io; +#![deny(warnings, rust_2018_idioms)] pub extern crate test; @@ -22,7 +16,7 @@ mod prelude { } mod connect_churn { - use prelude::*; + use crate::prelude::*; const NUM: usize = 300; const CONCURRENT: usize = 8; @@ -153,8 +147,9 @@ mod connect_churn { } mod transfer { - use prelude::*; + use crate::prelude::*; use std::{cmp, mem}; + use tokio_io::try_nb; const MB: usize = 3 * 1024 * 1024; @@ -242,7 +237,7 @@ mod transfer { } mod small_chunks { - use prelude::*; + use crate::prelude::*; #[bench] fn one_thread(b: &mut Bencher) { @@ -251,7 +246,7 @@ mod transfer { } mod big_chunks { - use prelude::*; + use crate::prelude::*; #[bench] fn one_thread(b: &mut Bencher) { diff --git a/tokio/examples/blocking.rs b/tokio/examples/blocking.rs index e7d5da6c8..9c2624210 100644 --- a/tokio/examples/blocking.rs +++ b/tokio/examples/blocking.rs @@ -9,11 +9,11 @@ //! Note how non-blocking threads are executed before blocking threads finish //! their task. -extern crate tokio; -extern crate tokio_threadpool; +#![deny(warnings, rust_2018_idioms)] use std::thread; use std::time::Duration; +use tokio; use tokio::prelude::*; use tokio::runtime::Builder; use tokio_threadpool::blocking; diff --git a/tokio/examples/chat-combinator-current-thread.rs b/tokio/examples/chat-combinator-current-thread.rs index ee147025d..c82c27118 100644 --- a/tokio/examples/chat-combinator-current-thread.rs +++ b/tokio/examples/chat-combinator-current-thread.rs @@ -24,24 +24,21 @@ //! connected clients they'll all join the same room and see everyone else's //! messages. -#![deny(warnings)] - -extern crate futures; -extern crate tokio; - -use tokio::io; -use tokio::net::TcpListener; -use tokio::prelude::*; -use tokio::runtime::current_thread::{Runtime, TaskExecutor}; +#![deny(warnings, rust_2018_idioms)] +use futures; use std::cell::RefCell; use std::collections::HashMap; use std::env; use std::io::BufReader; use std::iter; use std::rc::Rc; +use tokio::io; +use tokio::net::TcpListener; +use tokio::prelude::*; +use tokio::runtime::current_thread::{Runtime, TaskExecutor}; -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { let mut runtime = Runtime::new().unwrap(); // Create the TCP listener we'll accept connections on. diff --git a/tokio/examples/chat-combinator.rs b/tokio/examples/chat-combinator.rs index b81e8f7c3..4c42cdfff 100644 --- a/tokio/examples/chat-combinator.rs +++ b/tokio/examples/chat-combinator.rs @@ -19,22 +19,20 @@ //! connected clients they'll all join the same room and see everyone else's //! messages. -#![deny(warnings)] - -extern crate futures; -extern crate tokio; - -use tokio::io; -use tokio::net::TcpListener; -use tokio::prelude::*; +#![deny(warnings, rust_2018_idioms)] +use futures; use std::collections::HashMap; use std::env; use std::io::BufReader; use std::iter; use std::sync::{Arc, Mutex}; +use tokio; +use tokio::io; +use tokio::net::TcpListener; +use tokio::prelude::*; -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { // Create the TCP listener we'll accept connections on. let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string()); let addr = addr.parse()?; diff --git a/tokio/examples/chat.rs b/tokio/examples/chat.rs index b21432afa..eb2f51938 100644 --- a/tokio/examples/chat.rs +++ b/tokio/examples/chat.rs @@ -24,23 +24,19 @@ //! connected clients they'll all join the same room and see everyone else's //! messages. -#![deny(warnings)] - -extern crate tokio; -#[macro_use] -extern crate futures; -extern crate bytes; +#![deny(warnings, rust_2018_idioms)] use bytes::{BufMut, Bytes, BytesMut}; use futures::future::{self, Either}; use futures::sync::mpsc; -use tokio::io; -use tokio::net::{TcpListener, TcpStream}; -use tokio::prelude::*; - +use futures::try_ready; use std::collections::HashMap; use std::net::SocketAddr; use std::sync::{Arc, Mutex}; +use tokio; +use tokio::io; +use tokio::net::{TcpListener, TcpStream}; +use tokio::prelude::*; /// Shorthand for the transmit half of the message channel. type Tx = mpsc::UnboundedSender; @@ -422,7 +418,7 @@ fn process(socket: TcpStream, state: Arc>) { tokio::spawn(connection); } -pub fn main() -> Result<(), Box> { +pub fn main() -> Result<(), Box> { // Create the shared state. This is how all the peers communicate. // // The server task will hold a handle to this. For every new client, the diff --git a/tokio/examples/connect.rs b/tokio/examples/connect.rs index 4dc0ea31e..82908e94d 100644 --- a/tokio/examples/connect.rs +++ b/tokio/examples/connect.rs @@ -14,22 +14,17 @@ //! this repository! Many of them recommend running this as a simple "hook up //! stdin/stdout to a server" to get up and running. -#![deny(warnings)] - -extern crate bytes; -extern crate futures; -extern crate tokio; -extern crate tokio_io; +#![deny(warnings, rust_2018_idioms)] +use futures::sync::mpsc; use std::env; use std::io::{self, Read, Write}; use std::net::SocketAddr; use std::thread; - -use futures::sync::mpsc; +use tokio; use tokio::prelude::*; -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { // Determine if we're going to run in TCP or UDP mode let mut args = env::args().skip(1).collect::>(); let tcp = match args.iter().position(|a| a == "--udp") { @@ -124,8 +119,8 @@ mod tcp { use tokio::net::TcpStream; use tokio::prelude::*; + use crate::codec::Bytes; use bytes::BytesMut; - use codec::Bytes; use std::error::Error; use std::io; @@ -133,8 +128,8 @@ mod tcp { pub fn connect( addr: &SocketAddr, - stdin: Box, Error = io::Error> + Send>, - ) -> Result + Send>, Box> { + stdin: Box, Error = io::Error> + Send>, + ) -> Result + Send>, Box> { let tcp = TcpStream::connect(addr); // After the TCP connection has been established, we set up our client @@ -181,12 +176,12 @@ mod udp { use tokio::net::{UdpFramed, UdpSocket}; use tokio::prelude::*; - use codec::Bytes; + use crate::codec::Bytes; pub fn connect( &addr: &SocketAddr, - stdin: Box, Error = io::Error> + Send>, - ) -> Result + Send>, Box> { + stdin: Box, Error = io::Error> + Send>, + ) -> Result + Send>, Box> { // We'll bind our UDP socket to a local IP/port, but for now we // basically let the OS pick both of those. let addr_to_bind = if addr.ip().is_ipv4() { diff --git a/tokio/examples/echo-udp.rs b/tokio/examples/echo-udp.rs index 93ebca799..2452f735b 100644 --- a/tokio/examples/echo-udp.rs +++ b/tokio/examples/echo-udp.rs @@ -10,15 +10,12 @@ //! //! Each line you type in to the `nc` terminal should be echo'd back to you! -#![deny(warnings)] - -#[macro_use] -extern crate futures; -extern crate tokio; +#![deny(warnings, rust_2018_idioms)] +use futures::try_ready; use std::net::SocketAddr; use std::{env, io}; - +use tokio; use tokio::net::UdpSocket; use tokio::prelude::*; @@ -50,7 +47,7 @@ impl Future for Server { } } -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string()); let addr = addr.parse::()?; diff --git a/tokio/examples/echo.rs b/tokio/examples/echo.rs index 45f808f89..0b52490e3 100644 --- a/tokio/examples/echo.rs +++ b/tokio/examples/echo.rs @@ -19,18 +19,16 @@ //! you! If you open up multiple terminals running the `connect` example you //! should be able to see them all make progress simultaneously. -#![deny(warnings)] - -extern crate tokio; +#![deny(warnings, rust_2018_idioms)] +use std::env; +use std::net::SocketAddr; +use tokio; use tokio::io; use tokio::net::TcpListener; use tokio::prelude::*; -use std::env; -use std::net::SocketAddr; - -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { // Allow passing an address to listen on as the first argument of this // program, but otherwise we'll just set up our TCP listener on // 127.0.0.1:8080 for connections. diff --git a/tokio/examples/hello_world.rs b/tokio/examples/hello_world.rs index c82762691..3b8371549 100644 --- a/tokio/examples/hello_world.rs +++ b/tokio/examples/hello_world.rs @@ -11,15 +11,14 @@ //! //! cargo run --example hello_world -#![deny(warnings)] - -extern crate tokio; +#![deny(warnings, rust_2018_idioms)] +use tokio; use tokio::io; use tokio::net::TcpStream; use tokio::prelude::*; -pub fn main() -> Result<(), Box> { +pub fn main() -> Result<(), Box> { let addr = "127.0.0.1:6142".parse()?; // Open a TCP stream to the socket address. diff --git a/tokio/examples/manual-runtime.rs b/tokio/examples/manual-runtime.rs index 8e3e12996..592680c1a 100644 --- a/tokio/examples/manual-runtime.rs +++ b/tokio/examples/manual-runtime.rs @@ -8,18 +8,16 @@ //! Note that the error handling is a bit left out. Also, the `run` could be modified to return the //! result of the provided future. -extern crate futures; -extern crate tokio; -extern crate tokio_current_thread; -extern crate tokio_executor; -extern crate tokio_reactor; -extern crate tokio_timer; - -use std::io::Error as IoError; -use std::time::{Duration, Instant}; +#![deny(warnings, rust_2018_idioms)] use futures::{future, Future}; +use std::io::Error as IoError; +use std::time::{Duration, Instant}; +use tokio; +use tokio_current_thread; use tokio_current_thread::CurrentThread; +use tokio_executor; +use tokio_reactor; use tokio_reactor::Reactor; use tokio_timer::timer::{self, Timer}; @@ -60,7 +58,7 @@ fn run>(f: F) -> Result<(), IoError> { Ok(()) } -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { run(future::lazy(|| { // Here comes the application logic. It can spawn further tasks by tokio_current_thread::spawn(). // It also can use the default reactor and create timeouts. diff --git a/tokio/examples/print_each_packet.rs b/tokio/examples/print_each_packet.rs index 94a606483..f70510ee5 100644 --- a/tokio/examples/print_each_packet.rs +++ b/tokio/examples/print_each_packet.rs @@ -52,20 +52,17 @@ //! ``` //! -#![deny(warnings)] - -extern crate tokio; -extern crate tokio_codec; +#![deny(warnings, rust_2018_idioms)] +use std::env; +use std::net::SocketAddr; +use tokio; use tokio::codec::Decoder; use tokio::net::TcpListener; use tokio::prelude::*; use tokio_codec::BytesCodec; -use std::env; -use std::net::SocketAddr; - -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { // Allow passing an address to listen on as the first argument of this // program, but otherwise we'll just set up our TCP listener on // 127.0.0.1:8080 for connections. diff --git a/tokio/examples/proxy.rs b/tokio/examples/proxy.rs index 2cbcf119a..3f4e6754e 100644 --- a/tokio/examples/proxy.rs +++ b/tokio/examples/proxy.rs @@ -20,20 +20,18 @@ //! This final terminal will connect to our proxy, which will in turn connect to //! the echo server, and you'll be able to see data flowing between them. -#![deny(warnings)] - -extern crate tokio; +#![deny(warnings, rust_2018_idioms)] use std::env; use std::io::{self, Read, Write}; use std::net::{Shutdown, SocketAddr}; use std::sync::{Arc, Mutex}; - +use tokio; use tokio::io::{copy, shutdown}; use tokio::net::{TcpListener, TcpStream}; use tokio::prelude::*; -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { let listen_addr = env::args().nth(1).unwrap_or("127.0.0.1:8081".to_string()); let listen_addr = listen_addr.parse::()?; diff --git a/tokio/examples/tinydb.rs b/tokio/examples/tinydb.rs index 11298ed13..dde523553 100644 --- a/tokio/examples/tinydb.rs +++ b/tokio/examples/tinydb.rs @@ -39,16 +39,14 @@ //! * `SET $key $value` - this will set the value of `$key` to `$value`, //! returning the previous value, if any. -#![deny(warnings)] - -extern crate tokio; +#![deny(warnings, rust_2018_idioms)] use std::collections::HashMap; use std::env; use std::io::BufReader; use std::net::SocketAddr; use std::sync::{Arc, Mutex}; - +use tokio; use tokio::io::{lines, write_all}; use tokio::net::TcpListener; use tokio::prelude::*; @@ -83,7 +81,7 @@ enum Response { }, } -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { // Parse the address we're going to run this server on // and set up our TCP listener to accept connections. let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string()); diff --git a/tokio/examples/tinyhttp.rs b/tokio/examples/tinyhttp.rs index cde1b79af..028c8aa47 100644 --- a/tokio/examples/tinyhttp.rs +++ b/tokio/examples/tinyhttp.rs @@ -11,30 +11,23 @@ //! respectively. By default this will run I/O on all the cores your system has //! available, and it doesn't support HTTP request bodies. -#![deny(warnings)] - -extern crate bytes; -extern crate http; -extern crate httparse; -#[macro_use] -extern crate serde_derive; -extern crate serde_json; -extern crate time; -extern crate tokio; -extern crate tokio_io; +#![deny(warnings, rust_2018_idioms)] +use bytes::BytesMut; +use http; +use http::header::HeaderValue; +use http::{Request, Response, StatusCode}; +use httparse; +use serde::Serialize; +use serde_json; use std::net::SocketAddr; use std::{env, fmt, io}; - +use tokio; use tokio::codec::{Decoder, Encoder}; use tokio::net::{TcpListener, TcpStream}; use tokio::prelude::*; -use bytes::BytesMut; -use http::header::HeaderValue; -use http::{Request, Response, StatusCode}; - -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { // Parse the arguments, bind the TCP socket we'll be listening to, spin up // our worker threads, and start shipping sockets to those worker threads. let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string()); @@ -82,7 +75,7 @@ fn process(socket: TcpStream) { /// This function is a map from and HTTP request to a future of a response and /// represents the various handling a server might do. Currently the contents /// here are pretty uninteresting. -fn respond(req: Request<()>) -> Box, Error = io::Error> + Send> { +fn respond(req: Request<()>) -> Box, Error = io::Error> + Send> { let f = future::lazy(move || { let mut response = Response::builder(); let body = match req.uri().path() { @@ -163,7 +156,7 @@ impl Encoder for Http { Ok(()) } - fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result { + fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result { fmt::write(self, args) } } @@ -286,7 +279,7 @@ mod date { })); impl fmt::Display for Now { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { LAST.with(|cache| { let mut cache = cache.borrow_mut(); let now = time::get_time(); diff --git a/tokio/examples/udp-client.rs b/tokio/examples/udp-client.rs index 900d3616d..8cb7f5424 100644 --- a/tokio/examples/udp-client.rs +++ b/tokio/examples/udp-client.rs @@ -26,8 +26,7 @@ //! Please mind that since the UDP protocol doesn't have any capabilities to detect a broken //! connection the server needs to be run first, otherwise the client will block forever. -extern crate futures; -extern crate tokio; +#![deny(warnings, rust_2018_idioms)] use std::env; use std::io::stdin; @@ -35,13 +34,13 @@ use std::net::SocketAddr; use tokio::net::UdpSocket; use tokio::prelude::*; -fn get_stdin_data() -> Result, Box> { +fn get_stdin_data() -> Result, Box> { let mut buf = Vec::new(); stdin().read_to_end(&mut buf)?; Ok(buf) } -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { let remote_addr: SocketAddr = env::args() .nth(1) .unwrap_or("127.0.0.1:8080".into()) diff --git a/tokio/examples/udp-codec.rs b/tokio/examples/udp-codec.rs index 3657d8cc1..fc34253a2 100644 --- a/tokio/examples/udp-codec.rs +++ b/tokio/examples/udp-codec.rs @@ -6,20 +6,16 @@ //! new message with a new destination. Overall, we then use this to construct a //! "ping pong" pair where two sockets are sending messages back and forth. -#![deny(warnings)] - -extern crate env_logger; -extern crate tokio; -extern crate tokio_codec; -extern crate tokio_io; +#![deny(warnings, rust_2018_idioms)] +use env_logger; use std::net::SocketAddr; - +use tokio; use tokio::net::{UdpFramed, UdpSocket}; use tokio::prelude::*; use tokio_codec::BytesCodec; -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { let _ = env_logger::init(); let addr: SocketAddr = "127.0.0.1:0".parse()?; diff --git a/tokio/src/async_await.rs b/tokio/src/async_await.rs index ed8b52d07..29ebce88e 100644 --- a/tokio/src/async_await.rs +++ b/tokio/src/async_await.rs @@ -5,7 +5,7 @@ pub fn run_async(future: F) where F: std::future::Future + Send + 'static, { - ::run(compat::infallible_into_01(future)); + crate::run(compat::infallible_into_01(future)); } /// Like `tokio::spawn`, but takes an `async` block @@ -13,5 +13,5 @@ pub fn spawn_async(future: F) where F: std::future::Future + Send + 'static, { - ::spawn(compat::infallible_into_01(future)); + crate::spawn(compat::infallible_into_01(future)); } diff --git a/tokio/src/codec/length_delimited.rs b/tokio/src/codec/length_delimited.rs index 87393982b..37a3d1471 100644 --- a/tokio/src/codec/length_delimited.rs +++ b/tokio/src/codec/length_delimited.rs @@ -15,7 +15,6 @@ //! byte stream into a stream of frames. //! //! ``` -//! # extern crate tokio; //! use tokio::io::{AsyncRead, AsyncWrite}; //! use tokio::codec::*; //! @@ -40,16 +39,12 @@ //! Specifically, given the following: //! //! ``` -//! # extern crate tokio; -//! # extern crate bytes; -//! # extern crate futures; -//! # //! use tokio::io::{AsyncRead, AsyncWrite}; //! use tokio::codec::*; //! use bytes::Bytes; //! use futures::{Sink, Future}; //! -//! fn write_frame(io: T) -> Result<(), Box> { +//! fn write_frame(io: T) -> Result<(), Box> { //! let mut transport = Framed::new(io, LengthDelimitedCodec::new()); //! let frame = Bytes::from("hello world"); //! @@ -82,7 +77,6 @@ //! frame head in the yielded `BytesMut`. //! //! ``` -//! # extern crate tokio; //! # use tokio::io::AsyncRead; //! # use tokio::codec::length_delimited; //! # fn bind_read(io: T) { @@ -117,7 +111,6 @@ //! frame head in the yielded `BytesMut`. //! //! ``` -//! # extern crate tokio; //! # use tokio::io::AsyncRead; //! # use tokio::codec::length_delimited; //! # fn bind_read(io: T) { @@ -150,7 +143,6 @@ //! **includes** the frame head length. //! //! ``` -//! # extern crate tokio; //! # use tokio::io::AsyncRead; //! # use tokio::codec::length_delimited; //! # fn bind_read(io: T) { @@ -185,7 +177,6 @@ //! frame head, including the frame head in the yielded `BytesMut`. //! //! ``` -//! # extern crate tokio; //! # use tokio::io::AsyncRead; //! # use tokio::codec::length_delimited; //! # fn bind_read(io: T) { @@ -230,7 +221,6 @@ //! included. //! //! ``` -//! # extern crate tokio; //! # use tokio::io::AsyncRead; //! # use tokio::codec::length_delimited; //! # fn bind_read(io: T) { @@ -277,7 +267,6 @@ //! length. //! //! ``` -//! # extern crate tokio; //! # use tokio::io::AsyncRead; //! # use tokio::codec::length_delimited; //! # fn bind_read(io: T) { @@ -288,7 +277,6 @@ //! .num_skip(3) //! .new_read(io); //! # } -//! # pub fn main() {} //! ``` //! //! The following frame will be decoded as such: @@ -324,8 +312,6 @@ //! configuration: //! //! ``` -//! # extern crate tokio; -//! # extern crate bytes; //! # use tokio::io::AsyncWrite; //! # use tokio::codec::length_delimited; //! # use bytes::BytesMut; @@ -354,13 +340,11 @@ //! [`Encoder`]: ../trait.Encoder.html //! [`BytesMut`]: https://docs.rs/bytes/0.4/bytes/struct.BytesMut.html -use { +use crate::{ codec::{Decoder, Encoder, Framed, FramedRead, FramedWrite}, io::{AsyncRead, AsyncWrite}, }; - use bytes::{Buf, BufMut, Bytes, BytesMut, IntoBuf}; - use std::error::Error as StdError; use std::io::{self, Cursor}; use std::{cmp, fmt}; @@ -609,7 +593,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; /// # use tokio::io::AsyncRead; /// use tokio::codec::length_delimited::Builder; /// @@ -654,7 +637,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; /// # use tokio::io::AsyncRead; /// use tokio::codec::length_delimited::Builder; /// @@ -679,7 +661,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; /// # use tokio::io::AsyncRead; /// use tokio::codec::length_delimited::Builder; /// @@ -704,7 +685,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; /// # use tokio::io::AsyncRead; /// use tokio::codec::length_delimited::Builder; /// @@ -739,7 +719,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; /// # use tokio::io::AsyncRead; /// use tokio::codec::length_delimited::Builder; /// @@ -764,7 +743,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; /// # use tokio::io::AsyncRead; /// use tokio::codec::length_delimited::Builder; /// @@ -788,7 +766,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; /// # use tokio::io::AsyncRead; /// use tokio::codec::length_delimited::Builder; /// @@ -810,7 +787,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; /// # use tokio::io::AsyncRead; /// use tokio::codec::length_delimited::Builder; /// @@ -835,7 +811,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; /// # use tokio::io::AsyncRead; /// use tokio::codec::length_delimited::Builder; /// @@ -856,7 +831,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; /// # use tokio::io::AsyncRead; /// use tokio::codec::length_delimited::Builder; /// # pub fn main() { @@ -880,7 +854,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; /// # use tokio::io::AsyncRead; /// use tokio::codec::length_delimited::Builder; /// @@ -906,8 +879,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate bytes; /// # use tokio::io::AsyncWrite; /// # use tokio::codec::length_delimited; /// # use bytes::BytesMut; @@ -930,8 +901,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate bytes; /// # use tokio::io::{AsyncRead, AsyncWrite}; /// # use tokio::codec::length_delimited; /// # use bytes::BytesMut; @@ -964,13 +933,13 @@ impl Builder { // ===== impl FrameTooBig ===== impl fmt::Debug for FrameTooBig { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("FrameTooBig").finish() } } impl fmt::Display for FrameTooBig { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.description()) } } diff --git a/tokio/src/codec/mod.rs b/tokio/src/codec/mod.rs index b6a3bbcb0..19ba7fe42 100644 --- a/tokio/src/codec/mod.rs +++ b/tokio/src/codec/mod.rs @@ -10,10 +10,9 @@ //! [`Stream`]: https://docs.rs/futures/0.1/futures/stream/trait.Stream.html //! [transports]: https://tokio.rs/docs/going-deeper/frames/ -pub use tokio_codec::{ - BytesCodec, Decoder, Encoder, Framed, FramedParts, FramedRead, FramedWrite, LinesCodec, -}; - pub mod length_delimited; pub use self::length_delimited::LengthDelimitedCodec; +pub use tokio_codec::{ + BytesCodec, Decoder, Encoder, Framed, FramedParts, FramedRead, FramedWrite, LinesCodec, +}; diff --git a/tokio/src/executor/current_thread/mod.rs b/tokio/src/executor/current_thread/mod.rs index 6036aa997..aa5efb945 100644 --- a/tokio/src/executor/current_thread/mod.rs +++ b/tokio/src/executor/current_thread/mod.rs @@ -19,8 +19,6 @@ //! For example: //! //! ``` -//! # extern crate tokio; -//! # extern crate futures; //! # use tokio::executor::current_thread; //! use futures::future::lazy; //! @@ -47,8 +45,6 @@ //! More fine-grain control can be achieved by using [`CurrentThread`] directly. //! //! ``` -//! # extern crate tokio; -//! # extern crate futures; //! # use tokio::executor::current_thread::CurrentThread; //! use futures::future::{lazy, empty}; //! use std::time::Duration; @@ -141,7 +137,7 @@ impl<'a> Context<'a> { #[deprecated(since = "0.1.2", note = "use block_on_all instead")] #[doc(hidden)] pub fn run(f: F) -> R - where F: FnOnce(&mut Context) -> R + where F: FnOnce(&mut Context<'_>) -> R { let mut context = Context { cancel: Cell::new(false), diff --git a/tokio/src/executor/mod.rs b/tokio/src/executor/mod.rs index 8331e821f..41fb65a7a 100644 --- a/tokio/src/executor/mod.rs +++ b/tokio/src/executor/mod.rs @@ -95,12 +95,10 @@ pub struct Spawn(()); /// that processes each received connection. /// /// ```rust -/// # extern crate tokio; -/// # extern crate futures; /// # use futures::{Future, Stream}; /// use tokio::net::TcpListener; /// -/// # fn process(_: T) -> Box + Send> { +/// # fn process(_: T) -> Box + Send> { /// # unimplemented!(); /// # } /// # fn dox() { diff --git a/tokio/src/lib.rs b/tokio/src/lib.rs index 872f23cd8..d159bb581 100644 --- a/tokio/src/lib.rs +++ b/tokio/src/lib.rs @@ -1,6 +1,8 @@ #![doc(html_root_url = "https://docs.rs/tokio/0.1.19")] -#![deny(missing_docs, warnings, missing_debug_implementations)] +#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)] +#![cfg_attr(test, deny(warnings))] #![cfg_attr(feature = "async-await-preview", feature(async_await, await_macro))] +#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))] //! A runtime for writing reliable, asynchronous, and slim applications. //! @@ -28,8 +30,6 @@ //! A simple TCP echo server: //! //! ```no_run -//! extern crate tokio; -//! //! use tokio::prelude::*; //! use tokio::io::copy; //! use tokio::net::TcpListener; @@ -75,39 +75,6 @@ macro_rules! if_runtime { )*) } -#[macro_use] -extern crate futures; - -#[cfg(feature = "io")] -extern crate bytes; -#[cfg(feature = "reactor")] -extern crate mio; -#[cfg(feature = "rt-full")] -extern crate num_cpus; -#[cfg(feature = "codec")] -extern crate tokio_codec; -#[cfg(feature = "rt-full")] -extern crate tokio_current_thread; -#[cfg(feature = "fs")] -extern crate tokio_fs; -#[cfg(feature = "io")] -extern crate tokio_io; -#[cfg(feature = "reactor")] -extern crate tokio_reactor; -#[cfg(feature = "sync")] -extern crate tokio_sync; -#[cfg(feature = "tcp")] -extern crate tokio_tcp; -#[cfg(feature = "rt-full")] -extern crate tokio_threadpool; -#[cfg(feature = "timer")] -extern crate tokio_timer; -#[cfg(feature = "udp")] -extern crate tokio_udp; - -#[cfg(all(unix, feature = "uds"))] -extern crate tokio_uds; - #[cfg(feature = "timer")] pub mod clock; #[cfg(feature = "codec")] @@ -128,23 +95,15 @@ pub mod timer; pub mod util; if_runtime! { - extern crate tokio_executor; - extern crate tokio_trace_core; pub mod executor; pub mod runtime; - pub use executor::spawn; - pub use runtime::run; + pub use crate::executor::spawn; + pub use crate::runtime::run; } // ===== Experimental async/await support ===== -#[cfg(feature = "async-await-preview")] -extern crate tokio_futures; - -#[cfg(feature = "async-await-preview")] -extern crate tokio_macros; - #[cfg(feature = "async-await-preview")] mod async_await; @@ -152,7 +111,7 @@ mod async_await; pub use async_await::{run_async, spawn_async}; #[cfg(feature = "async-await-preview")] -pub use tokio_futures::await; +pub use tokio_futures::async_wait; #[cfg(feature = "async-await-preview")] pub use tokio_macros::{main, test}; diff --git a/tokio/src/prelude.rs b/tokio/src/prelude.rs index b1b5f85b5..e364e8bf1 100644 --- a/tokio/src/prelude.rs +++ b/tokio/src/prelude.rs @@ -10,15 +10,9 @@ //! //! The prelude may grow over time as additional items see ubiquitous use. -#[cfg(feature = "io")] -pub use tokio_io::{AsyncRead, AsyncWrite}; - -pub use util::{FutureExt, StreamExt}; - -pub use std::io::{Read, Write}; - +pub use crate::util::{FutureExt, StreamExt}; pub use futures::{future, stream, task, Async, AsyncSink, Future, IntoFuture, Poll, Sink, Stream}; - +pub use std::io::{Read, Write}; #[cfg(feature = "async-await-preview")] #[doc(inline)] pub use tokio_futures::{ @@ -26,3 +20,5 @@ pub use tokio_futures::{ sink::SinkExt, stream::StreamExt as StreamAsyncExt, }; +#[cfg(feature = "io")] +pub use tokio_io::{AsyncRead, AsyncWrite}; diff --git a/tokio/src/reactor/mod.rs b/tokio/src/reactor/mod.rs index 0e3f4eaab..89e1c0958 100644 --- a/tokio/src/reactor/mod.rs +++ b/tokio/src/reactor/mod.rs @@ -21,7 +21,6 @@ //! Let's start with a basic example, establishing a TCP connection. //! //! ```rust -//! # extern crate tokio; //! # fn dox() { //! use tokio::prelude::*; //! use tokio::net::TcpStream; @@ -135,10 +134,10 @@ //! [`std::io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html //! [`std::io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html +mod poll_evented; + +#[allow(deprecated)] +pub use self::poll_evented::PollEvented; pub use tokio_reactor::{ Background, Handle, PollEvented as PollEvented2, Reactor, Registration, Turn, }; - -mod poll_evented; -#[allow(deprecated)] -pub use self::poll_evented::PollEvented; diff --git a/tokio/src/reactor/poll_evented.rs b/tokio/src/reactor/poll_evented.rs index 74e5d2ed8..2b0551160 100644 --- a/tokio/src/reactor/poll_evented.rs +++ b/tokio/src/reactor/poll_evented.rs @@ -8,19 +8,17 @@ #![allow(deprecated, warnings)] +use crate::reactor::{Handle, Registration}; +use futures::{task, Async, Poll}; +use mio::event::Evented; +use mio::Ready; use std::fmt; use std::io::{self, Read, Write}; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::Relaxed; use std::sync::Mutex; - -use futures::{task, Async, Poll}; -use mio::event::Evented; -use mio::Ready; use tokio_io::{AsyncRead, AsyncWrite}; -use reactor::{Handle, Registration}; - #[deprecated(since = "0.1.2", note = "PollEvented2 instead")] #[doc(hidden)] pub struct PollEvented { @@ -40,7 +38,7 @@ struct Inner { } impl fmt::Debug for PollEvented { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PollEvented").field("io", &self.io).finish() } } diff --git a/tokio/src/runtime/current_thread/async_await.rs b/tokio/src/runtime/current_thread/async_await.rs index 7a2599414..1dc2356f5 100644 --- a/tokio/src/runtime/current_thread/async_await.rs +++ b/tokio/src/runtime/current_thread/async_await.rs @@ -1,5 +1,5 @@ -use super::Runtime; use std::future::Future; +use super::Runtime; impl Runtime { /// Like `block_on`, but takes an `async` block diff --git a/tokio/src/runtime/current_thread/builder.rs b/tokio/src/runtime/current_thread/builder.rs index 72960fadf..dbc19fc15 100644 --- a/tokio/src/runtime/current_thread/builder.rs +++ b/tokio/src/runtime/current_thread/builder.rs @@ -1,10 +1,8 @@ -use executor::current_thread::CurrentThread; -use runtime::current_thread::Runtime; - +use crate::executor::current_thread::CurrentThread; +use crate::runtime::current_thread::Runtime; use tokio_reactor::Reactor; use tokio_timer::clock::Clock; use tokio_timer::timer::Timer; - use std::io; /// Builds a Single-threaded runtime with custom configuration values. @@ -23,9 +21,6 @@ use std::io; /// # Examples /// /// ``` -/// extern crate tokio; -/// extern crate tokio_timer; -/// /// use tokio::runtime::current_thread::Builder; /// use tokio_timer::clock::Clock; /// diff --git a/tokio/src/runtime/current_thread/mod.rs b/tokio/src/runtime/current_thread/mod.rs index eb0358df0..9d325c939 100644 --- a/tokio/src/runtime/current_thread/mod.rs +++ b/tokio/src/runtime/current_thread/mod.rs @@ -24,8 +24,6 @@ //! For example: //! //! ``` -//! # extern crate tokio; -//! # extern crate futures; //! use tokio::runtime::current_thread::Runtime; //! use tokio::prelude::*; //! use std::thread; diff --git a/tokio/src/runtime/current_thread/runtime.rs b/tokio/src/runtime/current_thread/runtime.rs index e297e873d..92c5390b6 100644 --- a/tokio/src/runtime/current_thread/runtime.rs +++ b/tokio/src/runtime/current_thread/runtime.rs @@ -1,14 +1,11 @@ +use crate::runtime::current_thread::Builder; +use futures::{future, Future}; use tokio_current_thread::{self as current_thread, CurrentThread}; use tokio_current_thread::Handle as ExecutorHandle; -use runtime::current_thread::Builder; - +use tokio_executor; use tokio_reactor::{self, Reactor}; use tokio_timer::clock::{self, Clock}; use tokio_timer::timer::{self, Timer}; -use tokio_executor; - -use futures::{future, Future}; - use std::fmt; use std::error::Error; use std::io; @@ -76,11 +73,11 @@ where T: Future + Send + 'static, } } -impl ::executor::TypedExecutor for Handle +impl crate::executor::TypedExecutor for Handle where T: Future + Send + 'static, { - fn spawn(&mut self, future: T) -> Result<(), ::executor::SpawnError> { + fn spawn(&mut self, future: T) -> Result<(), crate::executor::SpawnError> { Handle::spawn(self, future) } } @@ -92,7 +89,7 @@ pub struct RunError { } impl fmt::Display for RunError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{}", self.inner) } } @@ -105,7 +102,7 @@ impl Error for RunError { // FIXME(taiki-e): When the minimum support version of tokio reaches Rust 1.30, // replace this with Error::source. #[allow(deprecated)] - fn cause(&self) -> Option<&Error> { + fn cause(&self) -> Option<&dyn Error> { self.inner.cause() } } @@ -147,8 +144,6 @@ impl Runtime { /// # Examples /// /// ```rust - /// # extern crate tokio; - /// # extern crate futures; /// # use futures::{future, Future, Stream}; /// use tokio::runtime::current_thread::Runtime; /// @@ -212,7 +207,7 @@ impl Runtime { } fn enter(&mut self, f: F) -> R - where F: FnOnce(&mut current_thread::Entered>) -> R + where F: FnOnce(&mut current_thread::Entered<'_, Timer>) -> R { let Runtime { ref reactor_handle, diff --git a/tokio/src/runtime/mod.rs b/tokio/src/runtime/mod.rs index 759616829..cadfd4406 100644 --- a/tokio/src/runtime/mod.rs +++ b/tokio/src/runtime/mod.rs @@ -36,12 +36,10 @@ //! [idle]. //! //! ```rust -//! # extern crate tokio; -//! # extern crate futures; //! # use futures::{Future, Stream}; //! use tokio::net::TcpListener; //! -//! # fn process(_: T) -> Box + Send> { +//! # fn process(_: T) -> Box + Send> { //! # unimplemented!(); //! # } //! # fn dox() { @@ -69,13 +67,11 @@ //! A [`Runtime`] instance can also be used directly. //! //! ```rust -//! # extern crate tokio; -//! # extern crate futures; //! # use futures::{Future, Stream}; //! use tokio::runtime::Runtime; //! use tokio::net::TcpListener; //! -//! # fn process(_: T) -> Box + Send> { +//! # fn process(_: T) -> Box + Send> { //! # unimplemented!(); //! # } //! # fn dox() { @@ -122,4 +118,3 @@ pub use self::threadpool::{ TaskExecutor, run, }; - diff --git a/tokio/src/runtime/threadpool/async_await.rs b/tokio/src/runtime/threadpool/async_await.rs index 12bdb1a11..fc0d9af22 100644 --- a/tokio/src/runtime/threadpool/async_await.rs +++ b/tokio/src/runtime/threadpool/async_await.rs @@ -1,5 +1,5 @@ -use super::Runtime; use std::future::Future; +use super::Runtime; impl Runtime { /// Like `block_on`, but takes an `async` block diff --git a/tokio/src/runtime/threadpool/builder.rs b/tokio/src/runtime/threadpool/builder.rs index 030b3ca20..f85d0fa1e 100644 --- a/tokio/src/runtime/threadpool/builder.rs +++ b/tokio/src/runtime/threadpool/builder.rs @@ -1,18 +1,15 @@ -use super::{Inner, Runtime}; - -use reactor::Reactor; - -use std::io; -use std::sync::Mutex; -use std::time::Duration; -use std::any::Any; - +use crate::reactor::Reactor; use num_cpus; use tokio_reactor; use tokio_threadpool::Builder as ThreadPoolBuilder; use tokio_timer::clock::{self, Clock}; use tokio_timer::timer::{self, Timer}; use tokio_trace_core as trace; +use std::io; +use std::sync::Mutex; +use std::time::Duration; +use std::any::Any; +use super::{Inner, Runtime}; /// Builds Tokio Runtime with custom configuration values. /// @@ -30,9 +27,6 @@ use tokio_trace_core as trace; /// # Examples /// /// ``` -/// extern crate tokio; -/// extern crate tokio_timer; -/// /// use std::time::Duration; /// /// use tokio::runtime::Builder; @@ -113,8 +107,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// # use tokio::runtime; /// /// # pub fn main() { @@ -126,7 +118,7 @@ impl Builder { /// ``` pub fn panic_handler(&mut self, f: F) -> &mut Self where - F: Fn(Box) + Send + Sync + 'static, + F: Fn(Box) + Send + Sync + 'static, { self.threadpool_builder.panic_handler(f); self @@ -143,8 +135,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// # use tokio::runtime; /// /// # pub fn main() { @@ -175,8 +165,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// # use tokio::runtime; /// /// # pub fn main() { @@ -205,8 +193,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// # use tokio::runtime; /// use std::time::Duration; /// @@ -232,8 +218,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// # use tokio::runtime; /// /// # pub fn main() { @@ -258,8 +242,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// # use tokio::runtime; /// /// # pub fn main() { @@ -281,8 +263,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// # use tokio::runtime; /// /// # pub fn main() { @@ -307,8 +287,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// # use tokio::runtime; /// /// # pub fn main() { @@ -333,7 +311,6 @@ impl Builder { /// # Examples /// /// ``` - /// # extern crate tokio; /// # use tokio::runtime::Builder; /// # pub fn main() { /// let runtime = Builder::new().build().unwrap(); diff --git a/tokio/src/runtime/threadpool/mod.rs b/tokio/src/runtime/threadpool/mod.rs index b688a4674..b84edce39 100644 --- a/tokio/src/runtime/threadpool/mod.rs +++ b/tokio/src/runtime/threadpool/mod.rs @@ -9,16 +9,13 @@ pub use self::builder::Builder; pub use self::shutdown::Shutdown; pub use self::task_executor::TaskExecutor; -use reactor::{Handle, Reactor}; - -use std::io; -use std::sync::Mutex; - -use tokio_executor::enter; -use tokio_threadpool as threadpool; - +use crate::reactor::{Handle, Reactor}; use futures; use futures::future::Future; +use tokio_executor::enter; +use tokio_threadpool as threadpool; +use std::io; +use std::sync::Mutex; /// Handle to the Tokio runtime. /// @@ -70,12 +67,10 @@ struct Inner { /// # Examples /// /// ```rust -/// # extern crate tokio; -/// # extern crate futures; /// # use futures::{Future, Stream}; /// use tokio::net::TcpListener; /// -/// # fn process(_: T) -> Box + Send> { +/// # fn process(_: T) -> Box + Send> { /// # unimplemented!(); /// # } /// # fn dox() { @@ -216,8 +211,6 @@ impl Runtime { /// # Examples /// /// ```rust - /// # extern crate tokio; - /// # extern crate futures; /// # use futures::{future, Future, Stream}; /// use tokio::runtime::Runtime; /// diff --git a/tokio/src/runtime/threadpool/shutdown.rs b/tokio/src/runtime/threadpool/shutdown.rs index 66f814608..a1b3e7637 100644 --- a/tokio/src/runtime/threadpool/shutdown.rs +++ b/tokio/src/runtime/threadpool/shutdown.rs @@ -1,9 +1,7 @@ -use super::Inner; +use futures::{try_ready, Future, Poll}; use tokio_threadpool as threadpool; - use std::fmt; - -use futures::{Future, Poll}; +use super::Inner; /// A future that resolves when the Tokio `Runtime` is shut down. pub struct Shutdown { @@ -28,7 +26,7 @@ impl Future for Shutdown { } impl fmt::Debug for Shutdown { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Shutdown") .field("inner", &"Box>") .finish() diff --git a/tokio/src/runtime/threadpool/task_executor.rs b/tokio/src/runtime/threadpool/task_executor.rs index 91c665820..8c0c6aa09 100644 --- a/tokio/src/runtime/threadpool/task_executor.rs +++ b/tokio/src/runtime/threadpool/task_executor.rs @@ -1,7 +1,5 @@ - -use tokio_threadpool::Sender; - use futures::future::{self, Future}; +use tokio_threadpool::Sender; /// Executes futures on the runtime /// @@ -28,8 +26,6 @@ impl TaskExecutor { /// # Examples /// /// ```rust - /// # extern crate tokio; - /// # extern crate futures; /// # use futures::{future, Future, Stream}; /// use tokio::runtime::Runtime; /// @@ -66,19 +62,19 @@ where T: Future + Send + 'static, } } -impl ::executor::Executor for TaskExecutor { - fn spawn(&mut self, future: Box + Send>) - -> Result<(), ::executor::SpawnError> +impl crate::executor::Executor for TaskExecutor { + fn spawn(&mut self, future: Box + Send>) + -> Result<(), crate::executor::SpawnError> { self.inner.spawn(future) } } -impl ::executor::TypedExecutor for TaskExecutor +impl crate::executor::TypedExecutor for TaskExecutor where T: Future + Send + 'static, { - fn spawn(&mut self, future: T) -> Result<(), ::executor::SpawnError> { - ::executor::Executor::spawn(self, Box::new(future)) + fn spawn(&mut self, future: T) -> Result<(), crate::executor::SpawnError> { + crate::executor::Executor::spawn(self, Box::new(future)) } } diff --git a/tokio/src/timer.rs b/tokio/src/timer.rs index 888e7a9db..98de0018f 100644 --- a/tokio/src/timer.rs +++ b/tokio/src/timer.rs @@ -52,13 +52,11 @@ //! included in the prelude. //! //! ``` -//! # extern crate futures; -//! # extern crate tokio; //! use tokio::prelude::*; //! -//! use std::time::{Duration, Instant}; +//! use std::time::Duration; //! -//! fn long_op() -> Box + Send> { +//! fn long_op() -> Box + Send> { //! // ... //! # Box::new(futures::future::ok(())) //! } diff --git a/tokio/src/util/enumerate.rs b/tokio/src/util/enumerate.rs index 8f6926fa4..a3b916288 100644 --- a/tokio/src/util/enumerate.rs +++ b/tokio/src/util/enumerate.rs @@ -1,4 +1,4 @@ -use futures::{Async, Poll, Sink, StartSend, Stream}; +use futures::{try_ready, Async, Poll, Sink, StartSend, Stream}; /// A stream combinator which combines the yields the current item /// plus its count starting from 0. diff --git a/tokio/src/util/future.rs b/tokio/src/util/future.rs index 5a3818101..ea9d0ff39 100644 --- a/tokio/src/util/future.rs +++ b/tokio/src/util/future.rs @@ -1,11 +1,12 @@ +use futures::Future; + #[cfg(feature = "timer")] #[allow(deprecated)] use tokio_timer::Deadline; + #[cfg(feature = "timer")] use tokio_timer::Timeout; -use futures::Future; - #[cfg(feature = "timer")] use std::time::{Duration, Instant}; @@ -38,8 +39,6 @@ pub trait FutureExt: Future { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::prelude::*; /// use std::time::Duration; /// # use futures::future::{self, FutureResult}; @@ -81,7 +80,7 @@ impl FutureExt for T where T: Future {} #[cfg(test)] mod test { use super::*; - use prelude::future; + use crate::prelude::future; #[cfg(feature = "timer")] #[test] diff --git a/tokio/src/util/stream.rs b/tokio/src/util/stream.rs index 3b7aa2686..9b2d08522 100644 --- a/tokio/src/util/stream.rs +++ b/tokio/src/util/stream.rs @@ -1,11 +1,10 @@ -#[cfg(feature = "timer")] -use tokio_timer::{throttle::Throttle, Timeout}; +pub use crate::util::enumerate::Enumerate; use futures::Stream; - #[cfg(feature = "timer")] use std::time::Duration; -pub use util::enumerate::Enumerate; +#[cfg(feature = "timer")] +use tokio_timer::{throttle::Throttle, Timeout}; /// An extension trait for `Stream` that provides a variety of convenient /// combinator functions. @@ -63,8 +62,6 @@ pub trait StreamExt: Stream { /// # Examples /// /// ``` - /// # extern crate tokio; - /// # extern crate futures; /// use tokio::prelude::*; /// use std::time::Duration; /// # use futures::future::{self, FutureResult}; diff --git a/tokio/tests/buffered.rs b/tokio/tests/buffered.rs index 45560ad20..1cb5b09f8 100644 --- a/tokio/tests/buffered.rs +++ b/tokio/tests/buffered.rs @@ -1,14 +1,11 @@ -extern crate env_logger; -extern crate futures; -extern crate tokio; -extern crate tokio_io; +#![deny(warnings, rust_2018_idioms)] +use env_logger; +use futures::stream::Stream; +use futures::Future; use std::io::{BufReader, BufWriter, Read, Write}; use std::net::TcpStream; use std::thread; - -use futures::stream::Stream; -use futures::Future; use tokio::net::TcpListener; use tokio_io::io::copy; diff --git a/tokio/tests/clock.rs b/tokio/tests/clock.rs index 184705aed..9d4b22544 100644 --- a/tokio/tests/clock.rs +++ b/tokio/tests/clock.rs @@ -1,16 +1,14 @@ -extern crate env_logger; -extern crate futures; -extern crate tokio; -extern crate tokio_timer; +#![deny(warnings, rust_2018_idioms)] +use env_logger; +use std::sync::mpsc; +use std::time::{Duration, Instant}; use tokio::prelude::*; use tokio::runtime::{self, current_thread}; use tokio::timer::*; +use tokio_timer; use tokio_timer::clock::Clock; -use std::sync::mpsc; -use std::time::{Duration, Instant}; - struct MockNow(Instant); impl tokio_timer::clock::Now for MockNow { diff --git a/tokio/tests/drop-core.rs b/tokio/tests/drop-core.rs index 8be0d711d..d735c3437 100644 --- a/tokio/tests/drop-core.rs +++ b/tokio/tests/drop-core.rs @@ -1,12 +1,10 @@ -extern crate futures; -extern crate tokio; - -use std::net; -use std::thread; +#![deny(warnings, rust_2018_idioms)] use futures::future; use futures::prelude::*; use futures::sync::oneshot; +use std::net; +use std::thread; use tokio::net::TcpListener; use tokio::reactor::Reactor; diff --git a/tokio/tests/enumerate.rs b/tokio/tests/enumerate.rs index c71b7a24c..76367a322 100644 --- a/tokio/tests/enumerate.rs +++ b/tokio/tests/enumerate.rs @@ -1,7 +1,4 @@ -extern crate futures; -extern crate tokio; -extern crate tokio_executor; -extern crate tokio_timer; +#![deny(warnings, rust_2018_idioms)] use futures::sync::mpsc; use tokio::util::StreamExt; diff --git a/tokio/tests/global.rs b/tokio/tests/global.rs index 1bf45a66f..43052f12d 100644 --- a/tokio/tests/global.rs +++ b/tokio/tests/global.rs @@ -1,16 +1,15 @@ -extern crate env_logger; -extern crate futures; -extern crate tokio; -extern crate tokio_io; +#![deny(warnings, rust_2018_idioms)] +use env_logger; +use futures::prelude::*; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::Relaxed; use std::sync::Arc; use std::{io, thread}; - -use futures::prelude::*; +use tokio; use tokio::net::{TcpListener, TcpStream}; use tokio::runtime::Runtime; +use tokio_io; macro_rules! t { ($e:expr) => { diff --git a/tokio/tests/length_delimited.rs b/tokio/tests/length_delimited.rs index f87cfa936..65ab5564a 100644 --- a/tokio/tests/length_delimited.rs +++ b/tokio/tests/length_delimited.rs @@ -1,16 +1,12 @@ -extern crate bytes; -extern crate futures; -extern crate tokio; - -use tokio::codec::*; -use tokio::io::{AsyncRead, AsyncWrite}; +#![deny(warnings, rust_2018_idioms)] use bytes::{BufMut, Bytes, BytesMut}; use futures::Async::*; use futures::{Poll, Sink, Stream}; - use std::collections::VecDeque; use std::io; +use tokio::codec::*; +use tokio::io::{AsyncRead, AsyncWrite}; macro_rules! mock { ($($x:expr,)*) => {{ diff --git a/tokio/tests/line-frames.rs b/tokio/tests/line-frames.rs index 84b860a2a..35629683d 100644 --- a/tokio/tests/line-frames.rs +++ b/tokio/tests/line-frames.rs @@ -1,16 +1,10 @@ -extern crate bytes; -extern crate env_logger; -extern crate futures; -extern crate tokio; -extern crate tokio_codec; -extern crate tokio_io; -extern crate tokio_threadpool; - -use std::io; -use std::net::Shutdown; +#![deny(warnings, rust_2018_idioms)] use bytes::{BufMut, BytesMut}; +use env_logger; use futures::{Future, Sink, Stream}; +use std::io; +use std::net::Shutdown; use tokio::net::{TcpListener, TcpStream}; use tokio_codec::{Decoder, Encoder}; use tokio_io::io::{read, write_all}; diff --git a/tokio/tests/pipe-hup.rs b/tokio/tests/pipe-hup.rs index eabdec4c8..bb1992873 100644 --- a/tokio/tests/pipe-hup.rs +++ b/tokio/tests/pipe-hup.rs @@ -1,22 +1,18 @@ #![cfg(unix)] +#![deny(warnings, rust_2018_idioms)] -extern crate env_logger; -extern crate futures; -extern crate libc; -extern crate mio; -extern crate tokio; -extern crate tokio_io; - +use env_logger; +use futures::Future; +use libc; +use mio; +use mio::event::Evented; +use mio::unix::{EventedFd, UnixReady}; +use mio::{PollOpt, Ready, Token}; use std::fs::File; use std::io::{self, Write}; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::thread; use std::time::Duration; - -use futures::Future; -use mio::event::Evented; -use mio::unix::{EventedFd, UnixReady}; -use mio::{PollOpt, Ready, Token}; use tokio::reactor::{Handle, PollEvented2}; use tokio_io::io::read_to_end; diff --git a/tokio/tests/reactor.rs b/tokio/tests/reactor.rs index fd3a8eea6..1f8b9902b 100644 --- a/tokio/tests/reactor.rs +++ b/tokio/tests/reactor.rs @@ -1,17 +1,14 @@ -extern crate futures; -extern crate tokio_executor; -extern crate tokio_reactor; -extern crate tokio_tcp; - -use tokio_reactor::Reactor; -use tokio_tcp::TcpListener; +#![deny(warnings, rust_2018_idioms)] use futures::executor::{spawn, Notify, Spawn}; use futures::{Future, Stream}; - use std::mem; use std::net::TcpStream; use std::sync::{Arc, Mutex}; +use tokio_executor; +use tokio_reactor; +use tokio_reactor::Reactor; +use tokio_tcp::TcpListener; #[test] fn test_drop_on_notify() { @@ -30,7 +27,7 @@ fn test_drop_on_notify() { struct MyNotify; - type Task = Mutex>>>; + type Task = Mutex>>>; impl Notify for MyNotify { fn notify(&self, _: usize) { @@ -66,7 +63,7 @@ fn test_drop_on_notify() { .incoming() .for_each(|_| Ok(())) .map_err(|_| panic!()) - }) as Box>; + }) as Box>; let task = Arc::new(Mutex::new(spawn(task))); let notify = Arc::new(MyNotify); diff --git a/tokio/tests/runtime.rs b/tokio/tests/runtime.rs index f84c66738..6f47cfa45 100644 --- a/tokio/tests/runtime.rs +++ b/tokio/tests/runtime.rs @@ -1,10 +1,11 @@ -extern crate env_logger; -extern crate futures; -extern crate tokio; +#![deny(warnings, rust_2018_idioms)] +use env_logger; +use futures; use futures::sync::oneshot; use std::sync::{atomic, Arc, Mutex}; use std::thread; +use tokio; use tokio::io; use tokio::net::{TcpListener, TcpStream}; use tokio::prelude::future::lazy; @@ -25,7 +26,7 @@ macro_rules! t { }; } -fn create_client_server_future() -> Box + Send> { +fn create_client_server_future() -> Box + Send> { let server = t!(TcpListener::bind(&"127.0.0.1:0".parse().unwrap())); let addr = t!(server.local_addr()); let client = TcpStream::connect(&addr); @@ -84,7 +85,7 @@ mod runtime_single_threaded_block_on_all { fn test(spawn: F) where - F: Fn(Box + Send>), + F: Fn(Box + Send>), { let cnt = Arc::new(Mutex::new(0)); let c = cnt.clone(); @@ -133,7 +134,10 @@ mod runtime_single_threaded_racy { use super::*; fn test(spawn: F) where - F: Fn(tokio::runtime::current_thread::Handle, Box + Send>), + F: Fn( + tokio::runtime::current_thread::Handle, + Box + Send>, + ), { let (trigger, exit) = futures::sync::oneshot::channel(); let (handle_tx, handle_rx) = ::std::sync::mpsc::channel(); @@ -218,7 +222,7 @@ fn block_on_timer() { use std::time::{Duration, Instant}; use tokio::timer::{Delay, Error}; - fn after_1s(x: T) -> Box + Send> + fn after_1s(x: T) -> Box + Send> where T: Send + 'static, { @@ -235,7 +239,7 @@ mod from_block_on { fn test(spawn: F) where - F: Fn(Box + Send>) + Send + 'static, + F: Fn(Box + Send>) + Send + 'static, { let cnt = Arc::new(Mutex::new(0)); let c = cnt.clone(); @@ -317,7 +321,7 @@ mod many { const ITER: usize = 200; fn test(spawn: F) where - F: Fn(&mut Runtime, Box + Send>), + F: Fn(&mut Runtime, Box + Send>), { let cnt = Arc::new(Mutex::new(0)); let mut runtime = Runtime::new().unwrap(); @@ -360,7 +364,7 @@ mod from_block_on_all { fn test(spawn: F) where - F: Fn(Box + Send>) + Send + 'static, + F: Fn(Box + Send>) + Send + 'static, { let cnt = Arc::new(Mutex::new(0)); let c = cnt.clone(); @@ -414,8 +418,8 @@ mod nested_enter { fn test(first: F1, nested: F2) where - F1: Fn(Box + Send>) + Send + 'static, - F2: Fn(Box + Send>) + panic::UnwindSafe + Send + 'static, + F1: Fn(Box + Send>) + Send + 'static, + F2: Fn(Box + Send>) + panic::UnwindSafe + Send + 'static, { let panicked = Arc::new(Mutex::new(false)); let panicked2 = panicked.clone(); diff --git a/tokio/tests/timer.rs b/tokio/tests/timer.rs index 54c3b9d31..8cf8ab844 100644 --- a/tokio/tests/timer.rs +++ b/tokio/tests/timer.rs @@ -1,13 +1,11 @@ -extern crate env_logger; -extern crate futures; -extern crate tokio; -extern crate tokio_io; - -use tokio::prelude::*; -use tokio::timer::*; +#![deny(warnings, rust_2018_idioms)] +use env_logger; use std::sync::mpsc; use std::time::{Duration, Instant}; +use tokio; +use tokio::prelude::*; +use tokio::timer::*; #[test] fn timer_with_runtime() {