From a78d83b36c3ba1442ae8ffa99c845ecb1fa5f3f0 Mon Sep 17 00:00:00 2001 From: Oleg Nosov Date: Fri, 14 Feb 2020 02:12:18 +0300 Subject: [PATCH] Misc docs fixes (#2067) --- examples/functional/src/main.rs | 6 +- examples/imperative/src/main.rs | 4 +- futures-channel/benches/sync_mpsc.rs | 15 +- futures-channel/src/lib.rs | 4 - futures-channel/src/mpsc/mod.rs | 16 +- futures-channel/src/oneshot.rs | 2 +- futures-channel/tests/channel.rs | 10 +- futures-channel/tests/mpsc-close.rs | 4 +- futures-channel/tests/mpsc.rs | 33 ++- futures-channel/tests/oneshot.rs | 4 +- futures-core/src/future.rs | 10 +- futures-core/src/lib.rs | 10 +- futures-core/src/stream.rs | 43 ++-- .../src/task/__internal/atomic_waker.rs | 19 +- futures-core/src/task/mod.rs | 2 +- futures-core/src/task/poll.rs | 13 +- futures-executor/benches/thread_notify.rs | 5 +- futures-executor/src/lib.rs | 7 +- futures-executor/src/local_pool.rs | 14 +- futures-executor/src/thread_pool.rs | 49 ++--- futures-executor/src/unpark_mutex.rs | 29 +-- futures-executor/tests/local_pool.rs | 187 ++++++++++------ futures-io/src/lib.rs | 193 +++++++++-------- futures-macro/src/join.rs | 8 +- futures-macro/src/lib.rs | 2 - futures-macro/src/select.rs | 45 ++-- futures-sink/src/lib.rs | 17 +- futures-task/src/future_obj.rs | 45 ++-- futures-task/src/lib.rs | 8 +- futures-task/src/noop_waker.rs | 8 +- futures-task/src/spawn.rs | 2 +- futures-test/src/assert.rs | 12 +- futures-test/src/future/assert_unmoved.rs | 11 +- futures-test/src/future/pending_once.rs | 14 +- futures-test/src/interleave_pending.rs | 34 +-- futures-test/src/io/limited.rs | 15 +- futures-test/src/lib.rs | 6 +- futures-test/src/task/context.rs | 2 +- futures-test/src/task/mod.rs | 2 +- futures-test/src/task/panic_waker.rs | 10 +- futures-test/src/task/wake_counter.rs | 2 +- futures-util/benches/futures_unordered.rs | 4 +- futures-util/src/async_await/pending.rs | 2 +- futures-util/src/async_await/poll.rs | 2 +- futures-util/src/compat/compat01as03.rs | 75 +++---- futures-util/src/compat/compat03as01.rs | 56 ++--- futures-util/src/compat/executor.rs | 4 +- futures-util/src/compat/mod.rs | 6 +- futures-util/src/future/either.rs | 5 +- .../src/future/future/catch_unwind.rs | 10 +- futures-util/src/future/future/chain.rs | 24 ++- futures-util/src/future/future/flatten.rs | 35 +-- .../src/future/future/flatten_stream.rs | 23 +- futures-util/src/future/future/fuse.rs | 6 +- futures-util/src/future/future/inspect.rs | 19 +- futures-util/src/future/future/into_stream.rs | 8 +- futures-util/src/future/future/map.rs | 27 +-- futures-util/src/future/future/never_error.rs | 7 +- .../src/future/future/remote_handle.rs | 10 +- futures-util/src/future/future/shared.rs | 21 +- futures-util/src/future/future/then.rs | 27 +-- futures-util/src/future/future/unit_error.rs | 7 +- futures-util/src/future/join.rs | 6 +- futures-util/src/future/join_all.rs | 22 +- futures-util/src/future/lazy.rs | 15 +- futures-util/src/future/maybe_done.rs | 2 +- futures-util/src/future/option.rs | 7 +- futures-util/src/future/pending.rs | 7 +- futures-util/src/future/poll_fn.rs | 5 +- futures-util/src/future/select.rs | 10 +- futures-util/src/future/select_all.rs | 19 +- futures-util/src/future/select_ok.rs | 24 +-- .../src/future/try_future/and_then.rs | 31 ++- .../src/future/try_future/err_into.rs | 27 ++- .../src/future/try_future/flatten_sink.rs | 4 +- .../future/try_future/flatten_stream_sink.rs | 18 +- .../src/future/try_future/into_future.rs | 9 +- futures-util/src/future/try_future/map_err.rs | 35 +-- futures-util/src/future/try_future/map_ok.rs | 31 ++- .../src/future/try_future/map_ok_or_else.rs | 44 ++-- futures-util/src/future/try_future/mod.rs | 6 +- futures-util/src/future/try_future/or_else.rs | 36 ++-- .../src/future/try_future/try_chain.rs | 32 ++- .../future/try_future/try_flatten_stream.rs | 8 +- .../src/future/try_future/unwrap_or_else.rs | 31 ++- futures-util/src/future/try_join.rs | 2 +- futures-util/src/future/try_join_all.rs | 29 +-- futures-util/src/future/try_select.rs | 17 +- futures-util/src/io/allow_std.rs | 90 +++++--- futures-util/src/io/buf_reader.rs | 14 +- futures-util/src/io/buf_writer.rs | 13 +- futures-util/src/io/chain.rs | 12 +- futures-util/src/io/copy.rs | 8 +- futures-util/src/io/copy_buf.rs | 13 +- futures-util/src/io/cursor.rs | 22 +- futures-util/src/io/flush.rs | 3 +- futures-util/src/io/into_sink.rs | 32 +-- futures-util/src/io/lines.rs | 11 +- futures-util/src/io/mod.rs | 87 ++++---- futures-util/src/io/read_exact.rs | 2 +- futures-util/src/io/read_line.rs | 9 +- futures-util/src/io/read_to_end.rs | 18 +- futures-util/src/io/read_to_string.rs | 5 +- futures-util/src/io/split.rs | 41 ++-- futures-util/src/io/take.rs | 6 +- futures-util/src/io/window.rs | 5 +- futures-util/src/io/write_all.rs | 2 +- futures-util/src/lib.rs | 23 +- futures-util/src/sink/buffer.rs | 42 ++-- futures-util/src/sink/close.rs | 10 +- futures-util/src/sink/drain.rs | 20 +- futures-util/src/sink/err_into.rs | 33 ++- futures-util/src/sink/fanout.rs | 52 +++-- futures-util/src/sink/flush.rs | 10 +- futures-util/src/sink/map_err.rs | 34 +-- futures-util/src/sink/mod.rs | 71 ++++--- futures-util/src/sink/send.rs | 10 +- futures-util/src/sink/send_all.rs | 35 +-- futures-util/src/sink/with.rs | 83 +++----- futures-util/src/sink/with_flat_map.rs | 46 +--- futures-util/src/stream/empty.rs | 6 +- futures-util/src/stream/iter.rs | 10 +- futures-util/src/stream/mod.rs | 4 +- futures-util/src/stream/once.rs | 4 +- futures-util/src/stream/repeat.rs | 11 +- futures-util/src/stream/select.rs | 45 ++-- .../src/stream/stream/catch_unwind.rs | 15 +- futures-util/src/stream/stream/chain.rs | 29 ++- futures-util/src/stream/stream/chunks.rs | 22 +- futures-util/src/stream/stream/collect.rs | 15 +- futures-util/src/stream/stream/concat.rs | 35 ++- futures-util/src/stream/stream/enumerate.rs | 10 +- futures-util/src/stream/stream/filter.rs | 46 ++-- futures-util/src/stream/stream/filter_map.rs | 36 ++-- futures-util/src/stream/stream/fold.rs | 33 ++- futures-util/src/stream/stream/for_each.rs | 30 +-- futures-util/src/stream/stream/forward.rs | 20 +- futures-util/src/stream/stream/fuse.rs | 5 +- futures-util/src/stream/stream/inspect.rs | 34 ++- futures-util/src/stream/stream/into_future.rs | 5 +- futures-util/src/stream/stream/map.rs | 34 ++- futures-util/src/stream/stream/mod.rs | 14 +- futures-util/src/stream/stream/next.rs | 5 +- futures-util/src/stream/stream/peek.rs | 14 +- futures-util/src/stream/stream/scan.rs | 9 +- .../src/stream/stream/select_next_some.rs | 4 +- futures-util/src/stream/stream/skip.rs | 10 +- futures-util/src/stream/stream/skip_while.rs | 48 ++--- futures-util/src/stream/stream/take.rs | 23 +- futures-util/src/stream/stream/take_while.rs | 41 ++-- futures-util/src/stream/stream/then.rs | 38 ++-- futures-util/src/stream/stream/zip.rs | 31 ++- .../src/stream/try_stream/and_then.rs | 31 +-- .../src/stream/try_stream/err_into.rs | 8 +- .../src/stream/try_stream/inspect_err.rs | 9 +- .../src/stream/try_stream/inspect_ok.rs | 9 +- .../src/stream/try_stream/into_async_read.rs | 81 +++---- .../src/stream/try_stream/into_stream.rs | 5 +- futures-util/src/stream/try_stream/map_err.rs | 9 +- futures-util/src/stream/try_stream/map_ok.rs | 9 +- futures-util/src/stream/try_stream/mod.rs | 5 +- futures-util/src/stream/try_stream/or_else.rs | 31 +-- .../src/stream/try_stream/try_collect.rs | 10 +- .../src/stream/try_stream/try_concat.rs | 9 +- .../src/stream/try_stream/try_filter.rs | 39 ++-- .../src/stream/try_stream/try_filter_map.rs | 28 ++- .../src/stream/try_stream/try_flatten.rs | 8 +- .../src/stream/try_stream/try_fold.rs | 42 ++-- .../src/stream/try_stream/try_for_each.rs | 20 +- .../src/stream/try_stream/try_next.rs | 5 +- .../src/stream/try_stream/try_skip_while.rs | 49 +++-- .../src/stream/try_stream/try_unfold.rs | 11 +- futures-util/src/stream/unfold.rs | 39 ++-- futures-util/src/task/mod.rs | 9 +- futures/src/lib.rs | 199 +++++++----------- futures/tests/arc_wake.rs | 9 +- futures/tests/async_await_macros.rs | 29 +-- futures/tests/basic_combinators.rs | 14 +- futures/tests/buffer_unordered.rs | 2 +- futures/tests/compat.rs | 12 +- futures/tests/eager_drop.rs | 16 +- futures/tests/future_obj.rs | 4 +- futures/tests/future_try_flatten_stream.rs | 4 +- futures/tests/futures_ordered.rs | 31 +-- futures/tests/futures_unordered.rs | 51 ++--- futures/tests/inspect.rs | 4 +- futures/tests/io_buf_reader.rs | 44 ++-- futures/tests/io_buf_writer.rs | 13 +- futures/tests/io_lines.rs | 8 +- futures/tests/io_read.rs | 5 +- futures/tests/io_read_exact.rs | 2 +- futures/tests/io_read_line.rs | 8 +- futures/tests/io_read_to_string.rs | 2 +- futures/tests/io_read_until.rs | 2 +- futures/tests/io_write.rs | 7 +- futures/tests/join_all.rs | 6 +- futures/tests/mutex.rs | 5 +- futures/tests/recurse.rs | 6 +- futures/tests/select_all.rs | 6 +- futures/tests/select_ok.rs | 13 +- futures/tests/shared.rs | 5 +- futures/tests/sink.rs | 34 +-- futures/tests/split.rs | 32 +-- futures/tests/stream.rs | 6 +- futures/tests/stream_into_async_read.rs | 4 +- futures/tests/stream_select_next_some.rs | 2 +- futures/tests/try_join.rs | 3 +- futures/tests/try_join_all.rs | 6 +- futures/tests/unfold.rs | 4 +- 209 files changed, 1920 insertions(+), 2469 deletions(-) diff --git a/examples/functional/src/main.rs b/examples/functional/src/main.rs index 3ce65de66a..7dea28d674 100644 --- a/examples/functional/src/main.rs +++ b/examples/functional/src/main.rs @@ -30,9 +30,7 @@ fn main() { // responsible for transmission pool.spawn_ok(fut_tx_result); - let fut_values = rx - .map(|v| v * 2) - .collect(); + let fut_values = rx.map(|v| v * 2).collect(); // Use the executor provided to this async block to wait for the // future to complete. @@ -45,4 +43,4 @@ fn main() { let values: Vec = executor::block_on(fut_values); println!("Values={:?}", values); -} \ No newline at end of file +} diff --git a/examples/imperative/src/main.rs b/examples/imperative/src/main.rs index ff1afffe27..10ef7f4df5 100644 --- a/examples/imperative/src/main.rs +++ b/examples/imperative/src/main.rs @@ -34,7 +34,7 @@ fn main() { // of the stream to be available. while let Some(v) = rx.next().await { pending.push(v * 2); - }; + } pending }; @@ -45,4 +45,4 @@ fn main() { let values: Vec = executor::block_on(fut_values); println!("Values={:?}", values); -} \ No newline at end of file +} diff --git a/futures-channel/benches/sync_mpsc.rs b/futures-channel/benches/sync_mpsc.rs index e22fe60666..7c3c3d3a80 100644 --- a/futures-channel/benches/sync_mpsc.rs +++ b/futures-channel/benches/sync_mpsc.rs @@ -7,8 +7,8 @@ use { futures::{ channel::mpsc::{self, Sender, UnboundedSender}, ready, - stream::{Stream, StreamExt}, sink::Sink, + stream::{Stream, StreamExt}, task::{Context, Poll}, }, futures_test::task::noop_context, @@ -25,7 +25,6 @@ fn unbounded_1_tx(b: &mut Bencher) { // 1000 iterations to avoid measuring overhead of initialization // Result should be divided by 1000 for i in 0..1000 { - // Poll, not ready, park assert_eq!(Poll::Pending, rx.poll_next_unpin(&mut cx)); @@ -73,7 +72,6 @@ fn unbounded_uncontended(b: &mut Bencher) { }) } - /// A Stream that continuously sends incrementing number of the queue struct TestSender { tx: Sender, @@ -84,9 +82,7 @@ struct TestSender { impl Stream for TestSender { type Item = u32; - fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) - -> Poll> - { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = &mut *self; let mut tx = Pin::new(&mut this.tx); @@ -123,12 +119,7 @@ fn bounded_100_tx(b: &mut Bencher) { // Each sender can send one item after specified capacity let (tx, mut rx) = mpsc::channel(0); - let mut tx: Vec<_> = (0..100).map(|_| { - TestSender { - tx: tx.clone(), - last: 0 - } - }).collect(); + let mut tx: Vec<_> = (0..100).map(|_| TestSender { tx: tx.clone(), last: 0 }).collect(); for i in 0..10 { for x in &mut tx { diff --git a/futures-channel/src/lib.rs b/futures-channel/src/lib.rs index d33c919b75..2f336ad5da 100644 --- a/futures-channel/src/lib.rs +++ b/futures-channel/src/lib.rs @@ -7,16 +7,12 @@ //! library is activated, and it is activated by default. #![cfg_attr(feature = "cfg-target-has-atomic", feature(cfg_target_has_atomic))] - #![cfg_attr(not(feature = "std"), no_std)] - #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms, unreachable_pub)] // It cannot be included in the published code because this lints have false positives in the minimum required version. #![cfg_attr(test, warn(single_use_lifetimes))] #![warn(clippy::all)] - #![doc(test(attr(deny(warnings), allow(dead_code, unused_assignments, unused_variables))))] - #![doc(html_root_url = "https://docs.rs/futures-channel/0.3.0")] #[cfg(all(feature = "cfg-target-has-atomic", not(feature = "unstable")))] diff --git a/futures-channel/src/mpsc/mod.rs b/futures-channel/src/mpsc/mod.rs index f69f440439..bce5e2e1e0 100644 --- a/futures-channel/src/mpsc/mod.rs +++ b/futures-channel/src/mpsc/mod.rs @@ -109,7 +109,7 @@ struct BoundedSenderInner { // unblocked. sender_task: Arc>, - // True if the sender might be blocked. This is an optimization to avoid + // `true` if the sender might be blocked. This is an optimization to avoid // having to lock the mutex most of the time. maybe_parked: bool, } @@ -189,7 +189,7 @@ impl fmt::Display for SendError { impl std::error::Error for SendError {} impl SendError { - /// Returns true if this error is a result of the channel being full. + /// Returns `true` if this error is a result of the channel being full. pub fn is_full(&self) -> bool { match self.kind { SendErrorKind::Full => true, @@ -197,7 +197,7 @@ impl SendError { } } - /// Returns true if this error is a result of the receiver being dropped. + /// Returns `true` if this error is a result of the receiver being dropped. pub fn is_disconnected(&self) -> bool { match self.kind { SendErrorKind::Disconnected => true, @@ -227,12 +227,12 @@ impl fmt::Display for TrySendError { impl std::error::Error for TrySendError {} impl TrySendError { - /// Returns true if this error is a result of the channel being full. + /// Returns `true` if this error is a result of the channel being full. pub fn is_full(&self) -> bool { self.err.is_full() } - /// Returns true if this error is a result of the receiver being dropped. + /// Returns `true` if this error is a result of the receiver being dropped. pub fn is_disconnected(&self) -> bool { self.err.is_disconnected() } @@ -536,7 +536,7 @@ impl BoundedSenderInner { // This operation will also atomically determine if the sender task // should be parked. // - // None is returned in the case that the channel has been closed by the + // `None` is returned in the case that the channel has been closed by the // receiver. This happens when `Receiver::close` is called or the // receiver is dropped. let park_self = match self.inc_num_messages() { @@ -997,7 +997,7 @@ impl Receiver { /// no longer empty. /// /// This function will panic if called after `try_next` or `poll_next` has - /// returned None. + /// returned `None`. pub fn try_next(&mut self) -> Result, TryRecvError> { match self.next_message() { Poll::Ready(msg) => { @@ -1127,7 +1127,7 @@ impl UnboundedReceiver { /// no longer empty. /// /// This function will panic if called after `try_next` or `poll_next` has - /// returned None. + /// returned `None`. pub fn try_next(&mut self) -> Result, TryRecvError> { match self.next_message() { Poll::Ready(msg) => { diff --git a/futures-channel/src/oneshot.rs b/futures-channel/src/oneshot.rs index d3be67e71e..d9f21d3083 100644 --- a/futures-channel/src/oneshot.rs +++ b/futures-channel/src/oneshot.rs @@ -126,7 +126,7 @@ impl Inner { } // Note that this lock acquisition may fail if the receiver - // is closed and sets the `complete` flag to true, whereupon + // is closed and sets the `complete` flag to `true`, whereupon // the receiver may call `poll()`. if let Some(mut slot) = self.data.try_lock() { assert!(slot.is_none()); diff --git a/futures-channel/tests/channel.rs b/futures-channel/tests/channel.rs index 73dac645b1..5f01a8ef4c 100644 --- a/futures-channel/tests/channel.rs +++ b/futures-channel/tests/channel.rs @@ -1,8 +1,8 @@ use futures::channel::mpsc; use futures::executor::block_on; use futures::future::poll_fn; -use futures::stream::StreamExt; use futures::sink::SinkExt; +use futures::stream::StreamExt; use std::sync::atomic::{AtomicUsize, Ordering}; use std::thread; @@ -11,9 +11,7 @@ fn sequence() { let (tx, rx) = mpsc::channel(1); let amt = 20; - let t = thread::spawn(move || { - block_on(send_sequence(amt, tx)) - }); + let t = thread::spawn(move || block_on(send_sequence(amt, tx))); let list: Vec<_> = block_on(rx.collect()); let mut list = list.into_iter(); for i in (1..=amt).rev() { @@ -34,9 +32,7 @@ async fn send_sequence(n: u32, mut sender: mpsc::Sender) { fn drop_sender() { let (tx, mut rx) = mpsc::channel::(1); drop(tx); - let f = poll_fn(|cx| { - rx.poll_next_unpin(cx) - }); + let f = poll_fn(|cx| rx.poll_next_unpin(cx)); assert_eq!(block_on(f), None) } diff --git a/futures-channel/tests/mpsc-close.rs b/futures-channel/tests/mpsc-close.rs index 50852eb71d..bf938936c4 100644 --- a/futures-channel/tests/mpsc-close.rs +++ b/futures-channel/tests/mpsc-close.rs @@ -9,9 +9,7 @@ use std::thread; fn smoke() { let (mut sender, receiver) = mpsc::channel(1); - let t = thread::spawn(move || { - while let Ok(()) = block_on(sender.send(42)) {} - }); + let t = thread::spawn(move || while let Ok(()) = block_on(sender.send(42)) {}); // `receiver` needs to be dropped for `sender` to stop sending and therefore before the join. block_on(receiver.take(3).for_each(|_| futures::future::ready(()))); diff --git a/futures-channel/tests/mpsc.rs b/futures-channel/tests/mpsc.rs index 409fa6e308..75f66a7ba9 100644 --- a/futures-channel/tests/mpsc.rs +++ b/futures-channel/tests/mpsc.rs @@ -1,13 +1,13 @@ use futures::channel::{mpsc, oneshot}; use futures::executor::{block_on, block_on_stream}; -use futures::future::{FutureExt, poll_fn}; -use futures::stream::{Stream, StreamExt}; +use futures::future::{poll_fn, FutureExt}; +use futures::pin_mut; use futures::sink::{Sink, SinkExt}; +use futures::stream::{Stream, StreamExt}; use futures::task::{Context, Poll}; -use futures::pin_mut; use futures_test::task::{new_count_waker, noop_context}; -use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; use std::thread; trait AssertSend: Send {} @@ -77,7 +77,7 @@ fn send_shared_recv() { fn send_recv_threads() { let (mut tx, rx) = mpsc::channel::(16); - let t = thread::spawn(move|| { + let t = thread::spawn(move || { block_on(tx.send(1)).unwrap(); }); @@ -204,7 +204,7 @@ fn stress_shared_unbounded() { const NTHREADS: u32 = 8; let (tx, rx) = mpsc::unbounded::(); - let t = thread::spawn(move|| { + let t = thread::spawn(move || { let result: Vec<_> = block_on(rx.collect()); assert_eq!(result.len(), (AMT * NTHREADS) as usize); for item in result { @@ -215,7 +215,7 @@ fn stress_shared_unbounded() { for _ in 0..NTHREADS { let tx = tx.clone(); - thread::spawn(move|| { + thread::spawn(move || { for _ in 0..AMT { tx.unbounded_send(1).unwrap(); } @@ -233,7 +233,7 @@ fn stress_shared_bounded_hard() { const NTHREADS: u32 = 8; let (tx, rx) = mpsc::channel::(0); - let t = thread::spawn(move|| { + let t = thread::spawn(move || { let result: Vec<_> = block_on(rx.collect()); assert_eq!(result.len(), (AMT * NTHREADS) as usize); for item in result { @@ -296,9 +296,9 @@ fn stress_receiver_multi_task_bounded_hard() { } Poll::Ready(None) => { *rx_opt = None; - break - }, - Poll::Pending => {}, + break; + } + Poll::Pending => {} } } } else { @@ -310,7 +310,6 @@ fn stress_receiver_multi_task_bounded_hard() { th.push(t); } - for i in 0..AMT { block_on(tx.send(i)).unwrap(); } @@ -327,7 +326,7 @@ fn stress_receiver_multi_task_bounded_hard() { /// after sender dropped. #[test] fn stress_drop_sender() { - fn list() -> impl Stream { + fn list() -> impl Stream { let (tx, rx) = mpsc::channel(1); thread::spawn(move || { block_on(send_one_two_three(tx)); @@ -405,9 +404,7 @@ fn stress_poll_ready() { let mut threads = Vec::new(); for _ in 0..NTHREADS { let sender = tx.clone(); - threads.push(thread::spawn(move || { - block_on(stress_poll_ready_sender(sender, AMT)) - })); + threads.push(thread::spawn(move || block_on(stress_poll_ready_sender(sender, AMT)))); } drop(tx); @@ -434,7 +431,7 @@ fn try_send_1() { for i in 0..N { loop { if tx.try_send(i).is_ok() { - break + break; } } } @@ -529,8 +526,8 @@ fn same_receiver() { #[test] fn hash_receiver() { - use std::hash::Hasher; use std::collections::hash_map::DefaultHasher; + use std::hash::Hasher; let mut hasher_a1 = DefaultHasher::new(); let mut hasher_a2 = DefaultHasher::new(); diff --git a/futures-channel/tests/oneshot.rs b/futures-channel/tests/oneshot.rs index 5194ce468f..b816b29d2f 100644 --- a/futures-channel/tests/oneshot.rs +++ b/futures-channel/tests/oneshot.rs @@ -1,6 +1,6 @@ use futures::channel::oneshot::{self, Sender}; use futures::executor::block_on; -use futures::future::{Future, FutureExt, poll_fn}; +use futures::future::{poll_fn, Future, FutureExt}; use futures::task::{Context, Poll}; use futures_test::task::panic_waker_ref; use std::pin::Pin; @@ -83,7 +83,7 @@ fn close() { rx.close(); block_on(poll_fn(|cx| { match rx.poll_unpin(cx) { - Poll::Ready(Err(_)) => {}, + Poll::Ready(Err(_)) => {} _ => panic!(), }; assert!(tx.poll_canceled(cx).is_ready()); diff --git a/futures-core/src/future.rs b/futures-core/src/future.rs index 35a0fd3baa..8a087957b9 100644 --- a/futures-core/src/future.rs +++ b/futures-core/src/future.rs @@ -66,14 +66,12 @@ pub trait TryFuture: Future + private_try_future::Sealed { /// This method is a stopgap for a compiler limitation that prevents us from /// directly inheriting from the `Future` trait; in the future it won't be /// needed. - fn try_poll( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll>; + fn try_poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll>; } impl TryFuture for F - where F: ?Sized + Future> +where + F: ?Sized + Future>, { type Ok = T; type Error = E; @@ -86,8 +84,8 @@ impl TryFuture for F #[cfg(feature = "alloc")] mod if_alloc { - use alloc::boxed::Box; use super::*; + use alloc::boxed::Box; impl FusedFuture for Box { fn is_terminated(&self) -> bool { diff --git a/futures-core/src/lib.rs b/futures-core/src/lib.rs index 85eff3e843..18d2a309a1 100644 --- a/futures-core/src/lib.rs +++ b/futures-core/src/lib.rs @@ -1,16 +1,12 @@ //! Core traits and types for asynchronous operations in Rust. #![cfg_attr(feature = "cfg-target-has-atomic", feature(cfg_target_has_atomic))] - #![cfg_attr(not(feature = "std"), no_std)] - #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms, unreachable_pub)] // It cannot be included in the published code because this lints have false positives in the minimum required version. #![cfg_attr(test, warn(single_use_lifetimes))] #![warn(clippy::all)] - #![doc(test(attr(deny(warnings), allow(dead_code, unused_assignments, unused_variables))))] - #![doc(html_root_url = "https://docs.rs/futures-core/0.3.0")] #[cfg(all(feature = "cfg-target-has-atomic", not(feature = "unstable")))] @@ -20,10 +16,12 @@ compile_error!("The `cfg-target-has-atomic` feature requires the `unstable` feat extern crate alloc; pub mod future; -#[doc(hidden)] pub use self::future::{Future, FusedFuture, TryFuture}; +#[doc(hidden)] +pub use self::future::{FusedFuture, Future, TryFuture}; pub mod stream; -#[doc(hidden)] pub use self::stream::{Stream, FusedStream, TryStream}; +#[doc(hidden)] +pub use self::stream::{FusedStream, Stream, TryStream}; #[macro_use] pub mod task; diff --git a/futures-core/src/stream.rs b/futures-core/src/stream.rs index 1f0f9a6e45..54df4c607e 100644 --- a/futures-core/src/stream.rs +++ b/futures-core/src/stream.rs @@ -55,10 +55,7 @@ pub trait Stream { /// this is difficult to guard against then the `fuse` adapter can be used /// to ensure that `poll_next` always returns `Ready(None)` in subsequent /// calls. - fn poll_next( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll>; + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll>; /// Returns the bounds on the remaining length of the stream. /// @@ -95,10 +92,7 @@ pub trait Stream { impl Stream for &mut S { type Item = S::Item; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { S::poll_next(Pin::new(&mut **self), cx) } @@ -114,10 +108,7 @@ where { type Item = ::Item; - fn poll_next( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.get_mut().as_mut().poll_next(cx) } @@ -177,35 +168,36 @@ pub trait TryStream: Stream + private_try_stream::Sealed { /// This method is a stopgap for a compiler limitation that prevents us from /// directly inheriting from the `Stream` trait; in the future it won't be /// needed. - fn try_poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) - -> Poll>>; + fn try_poll_next( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll>>; } impl TryStream for S - where S: ?Sized + Stream> +where + S: ?Sized + Stream>, { type Ok = T; type Error = E; - fn try_poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) - -> Poll>> - { + fn try_poll_next( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll>> { self.poll_next(cx) } } #[cfg(feature = "alloc")] mod if_alloc { - use alloc::boxed::Box; use super::*; + use alloc::boxed::Box; impl Stream for Box { type Item = S::Item; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { Pin::new(&mut **self).poll_next(cx) } @@ -218,10 +210,7 @@ mod if_alloc { impl Stream for std::panic::AssertUnwindSafe { type Item = S::Item; - fn poll_next( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { unsafe { self.map_unchecked_mut(|x| &mut x.0) }.poll_next(cx) } diff --git a/futures-core/src/task/__internal/atomic_waker.rs b/futures-core/src/task/__internal/atomic_waker.rs index 506737e35b..6482ed247a 100644 --- a/futures-core/src/task/__internal/atomic_waker.rs +++ b/futures-core/src/task/__internal/atomic_waker.rs @@ -1,7 +1,7 @@ use core::cell::UnsafeCell; use core::fmt; use core::sync::atomic::AtomicUsize; -use core::sync::atomic::Ordering::{Acquire, Release, AcqRel}; +use core::sync::atomic::Ordering::{AcqRel, Acquire, Release}; use core::task::Waker; /// A synchronization primitive for task wakeup. @@ -202,10 +202,7 @@ impl AtomicWaker { trait AssertSync: Sync {} impl AssertSync for Waker {} - AtomicWaker { - state: AtomicUsize::new(WAITING), - waker: UnsafeCell::new(None), - } + AtomicWaker { state: AtomicUsize::new(WAITING), waker: UnsafeCell::new(None) } } /// Registers the waker to be notified on calls to `wake`. @@ -275,8 +272,7 @@ impl AtomicWaker { // nothing to acquire, only release. In case of concurrent // wakers, we need to acquire their releases, so success needs // to do both. - let res = self.state.compare_exchange( - REGISTERING, WAITING, AcqRel, Acquire); + let res = self.state.compare_exchange(REGISTERING, WAITING, AcqRel, Acquire); match res { Ok(_) => { @@ -340,9 +336,7 @@ impl AtomicWaker { // // We just want to maintain memory safety. It is ok to drop the // call to `register`. - debug_assert!( - state == REGISTERING || - state == REGISTERING | WAKING); + debug_assert!(state == REGISTERING || state == REGISTERING | WAKING); } } } @@ -387,9 +381,8 @@ impl AtomicWaker { // not. // debug_assert!( - state == REGISTERING || - state == REGISTERING | WAKING || - state == WAKING); + state == REGISTERING || state == REGISTERING | WAKING || state == WAKING + ); None } } diff --git a/futures-core/src/task/mod.rs b/futures-core/src/task/mod.rs index 362b376e04..5dde0804fe 100644 --- a/futures-core/src/task/mod.rs +++ b/futures-core/src/task/mod.rs @@ -6,4 +6,4 @@ mod poll; #[doc(hidden)] pub mod __internal; -pub use core::task::{Context, Poll, Waker, RawWaker, RawWakerVTable}; +pub use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker}; diff --git a/futures-core/src/task/poll.rs b/futures-core/src/task/poll.rs index fc61683e76..ff19f10719 100644 --- a/futures-core/src/task/poll.rs +++ b/futures-core/src/task/poll.rs @@ -3,9 +3,12 @@ /// This macro bakes in propagation of `Pending` signals by returning early. #[macro_export] macro_rules! ready { - ($e:expr $(,)?) => (match $e { - $crate::core_reexport::task::Poll::Ready(t) => t, - $crate::core_reexport::task::Poll::Pending => - return $crate::core_reexport::task::Poll::Pending, - }) + ($e:expr $(,)?) => { + match $e { + $crate::core_reexport::task::Poll::Ready(t) => t, + $crate::core_reexport::task::Poll::Pending => { + return $crate::core_reexport::task::Poll::Pending + } + } + }; } diff --git a/futures-executor/benches/thread_notify.rs b/futures-executor/benches/thread_notify.rs index d8fbec4555..88d0447cf6 100644 --- a/futures-executor/benches/thread_notify.rs +++ b/futures-executor/benches/thread_notify.rs @@ -102,10 +102,7 @@ fn thread_yield_multi_thread(b: &mut Bencher) { }); b.iter(move || { - let y = Yield { - rem: NUM, - tx: tx.clone(), - }; + let y = Yield { rem: NUM, tx: tx.clone() }; block_on(y); }); diff --git a/futures-executor/src/lib.rs b/futures-executor/src/lib.rs index f267876ce5..d2cf4f4ab1 100644 --- a/futures-executor/src/lib.rs +++ b/futures-executor/src/lib.rs @@ -4,14 +4,11 @@ //! library is activated, and it is activated by default. #![cfg_attr(not(feature = "std"), no_std)] - #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms, unreachable_pub)] // It cannot be included in the published code because this lints have false positives in the minimum required version. #![cfg_attr(test, warn(single_use_lifetimes))] #![warn(clippy::all)] - #![doc(test(attr(deny(warnings), allow(dead_code, unused_assignments, unused_variables))))] - #![doc(html_root_url = "https://docs.rs/futures-executor/0.3.0")] #[cfg(feature = "std")] @@ -21,10 +18,10 @@ pub use crate::local_pool::{block_on, block_on_stream, BlockingStream, LocalPool #[cfg(feature = "thread-pool")] #[cfg(feature = "std")] -mod unpark_mutex; +mod thread_pool; #[cfg(feature = "thread-pool")] #[cfg(feature = "std")] -mod thread_pool; +mod unpark_mutex; #[cfg(feature = "thread-pool")] #[cfg(feature = "std")] pub use crate::thread_pool::{ThreadPool, ThreadPoolBuilder}; diff --git a/futures-executor/src/local_pool.rs b/futures-executor/src/local_pool.rs index b089a8094f..5631bb8e9f 100644 --- a/futures-executor/src/local_pool.rs +++ b/futures-executor/src/local_pool.rs @@ -10,7 +10,10 @@ use futures_util::stream::StreamExt; use std::cell::RefCell; use std::ops::{Deref, DerefMut}; use std::rc::{Rc, Weak}; -use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, +}; use std::thread::{self, Thread}; /// A single-threaded task pool for polling futures to completion. @@ -119,17 +122,12 @@ fn poll_executor) -> T>(mut f: F) -> T { impl LocalPool { /// Create a new, empty pool of tasks. pub fn new() -> LocalPool { - LocalPool { - pool: FuturesUnordered::new(), - incoming: Default::default(), - } + LocalPool { pool: FuturesUnordered::new(), incoming: Default::default() } } /// Get a clonable handle to the pool as a [`Spawn`]. pub fn spawner(&self) -> LocalSpawner { - LocalSpawner { - incoming: Rc::downgrade(&self.incoming), - } + LocalSpawner { incoming: Rc::downgrade(&self.incoming) } } /// Run all tasks in the pool to completion. diff --git a/futures-executor/src/thread_pool.rs b/futures-executor/src/thread_pool.rs index 6a87bc5f08..2f20ec1a52 100644 --- a/futures-executor/src/thread_pool.rs +++ b/futures-executor/src/thread_pool.rs @@ -2,8 +2,8 @@ use crate::enter; use crate::unpark_mutex::UnparkMutex; use futures_core::future::Future; use futures_core::task::{Context, Poll}; +use futures_task::{waker_ref, ArcWake}; use futures_task::{FutureObj, Spawn, SpawnError}; -use futures_task::{ArcWake, waker_ref}; use futures_util::future::FutureExt; use std::cmp; use std::fmt; @@ -52,9 +52,7 @@ struct PoolState { impl fmt::Debug for ThreadPool { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("ThreadPool") - .field("size", &self.state.size) - .finish() + f.debug_struct("ThreadPool").field("size", &self.state.size).finish() } } @@ -98,10 +96,7 @@ impl ThreadPool { pub fn spawn_obj_ok(&self, future: FutureObj<'static, ()>) { let task = Task { future, - wake_handle: Arc::new(WakeHandle { - exec: self.clone(), - mutex: UnparkMutex::new(), - }), + wake_handle: Arc::new(WakeHandle { exec: self.clone(), mutex: UnparkMutex::new() }), exec: self.clone(), }; self.state.send(Message::Run(task)); @@ -130,10 +125,7 @@ impl ThreadPool { } impl Spawn for ThreadPool { - fn spawn_obj( - &self, - future: FutureObj<'static, ()>, - ) -> Result<(), SpawnError> { + fn spawn_obj(&self, future: FutureObj<'static, ()>) -> Result<(), SpawnError> { self.spawn_obj_ok(future); Ok(()) } @@ -144,10 +136,12 @@ impl PoolState { self.tx.lock().unwrap().send(msg).unwrap(); } - fn work(&self, - idx: usize, - after_start: Option>, - before_stop: Option>) { + fn work( + &self, + idx: usize, + after_start: Option>, + before_stop: Option>, + ) { let _scope = enter().unwrap(); if let Some(after_start) = after_start { after_start(idx); @@ -239,7 +233,8 @@ impl ThreadPoolBuilder { /// The closure provided will receive an index corresponding to the worker /// thread it's running on. pub fn after_start(&mut self, f: F) -> &mut Self - where F: Fn(usize) + Send + Sync + 'static + where + F: Fn(usize) + Send + Sync + 'static, { self.after_start = Some(Arc::new(f)); self @@ -254,7 +249,8 @@ impl ThreadPoolBuilder { /// The closure provided will receive an index corresponding to the worker /// thread it's running on. pub fn before_stop(&mut self, f: F) -> &mut Self - where F: Fn(usize) + Send + Sync + 'static + where + F: Fn(usize) + Send + Sync + 'static, { self.before_stop = Some(Arc::new(f)); self @@ -326,14 +322,11 @@ impl Task { Poll::Pending => {} Poll::Ready(()) => return wake_handle.mutex.complete(), } - let task = Task { - future, - wake_handle: wake_handle.clone(), - exec, - }; + let task = Task { future, wake_handle: wake_handle.clone(), exec }; match wake_handle.mutex.wait(task) { Ok(()) => return, // we've waited - Err(task) => { // someone's notified us + Err(task) => { + // someone's notified us future = task.future; exec = task.exec; } @@ -345,9 +338,7 @@ impl Task { impl fmt::Debug for Task { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Task") - .field("contents", &"...") - .finish() + f.debug_struct("Task").field("contents", &"...").finish() } } @@ -370,7 +361,9 @@ mod tests { let (tx, rx) = mpsc::sync_channel(2); let _cpu_pool = ThreadPoolBuilder::new() .pool_size(2) - .after_start(move |_| tx.send(1).unwrap()).create().unwrap(); + .after_start(move |_| tx.send(1).unwrap()) + .create() + .unwrap(); // After ThreadPoolBuilder is deconstructed, the tx should be droped // so that we can use rx as an iterator. diff --git a/futures-executor/src/unpark_mutex.rs b/futures-executor/src/unpark_mutex.rs index 3497faac12..8365477404 100644 --- a/futures-executor/src/unpark_mutex.rs +++ b/futures-executor/src/unpark_mutex.rs @@ -29,25 +29,22 @@ unsafe impl Sync for UnparkMutex {} // transitions: // The task is blocked, waiting on an event -const WAITING: usize = 0; // --> POLLING +const WAITING: usize = 0; // --> POLLING // The task is actively being polled by a thread; arrival of additional events // of interest should move it to the REPOLL state -const POLLING: usize = 1; // --> WAITING, REPOLL, or COMPLETE +const POLLING: usize = 1; // --> WAITING, REPOLL, or COMPLETE // The task is actively being polled, but will need to be re-polled upon // completion to ensure that all events were observed. -const REPOLL: usize = 2; // --> POLLING +const REPOLL: usize = 2; // --> POLLING // The task has finished executing (either successfully or with an error/panic) -const COMPLETE: usize = 3; // No transitions out +const COMPLETE: usize = 3; // No transitions out impl UnparkMutex { pub(crate) fn new() -> UnparkMutex { - UnparkMutex { - status: AtomicUsize::new(WAITING), - inner: UnsafeCell::new(None), - } + UnparkMutex { status: AtomicUsize::new(WAITING), inner: UnsafeCell::new(None) } } /// Attempt to "notify" the mutex that a poll should occur. @@ -62,8 +59,7 @@ impl UnparkMutex { match status { // The task is idle, so try to run it immediately. WAITING => { - match self.status.compare_exchange(WAITING, POLLING, - SeqCst, SeqCst) { + match self.status.compare_exchange(WAITING, POLLING, SeqCst, SeqCst) { Ok(_) => { let data = unsafe { // SAFETY: we've ensured mutual exclusion via @@ -82,13 +78,10 @@ impl UnparkMutex { // The task is being polled, so we need to record that it should // be *repolled* when complete. - POLLING => { - match self.status.compare_exchange(POLLING, REPOLL, - SeqCst, SeqCst) { - Ok(_) => return Err(()), - Err(cur) => status = cur, - } - } + POLLING => match self.status.compare_exchange(POLLING, REPOLL, SeqCst, SeqCst) { + Ok(_) => return Err(()), + Err(cur) => status = cur, + }, // The task is already scheduled for polling, or is complete, so // we've got nothing to do. @@ -108,7 +101,7 @@ impl UnparkMutex { self.status.store(POLLING, SeqCst); } - /// Alert the mutex that polling completed with NotReady. + /// Alert the mutex that polling completed with `Pending`. /// /// # Safety /// diff --git a/futures-executor/tests/local_pool.rs b/futures-executor/tests/local_pool.rs index b31f1034cb..56e6daa077 100644 --- a/futures-executor/tests/local_pool.rs +++ b/futures-executor/tests/local_pool.rs @@ -1,14 +1,14 @@ use futures::channel::oneshot; use futures::executor::LocalPool; -use futures::future::{self, Future, lazy, poll_fn}; -use futures::task::{Context, Poll, Spawn, LocalSpawn, Waker}; +use futures::future::{self, lazy, poll_fn, Future}; +use futures::task::{Context, LocalSpawn, Poll, Spawn, Waker}; use std::cell::{Cell, RefCell}; use std::pin::Pin; use std::rc::Rc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; use std::thread; use std::time::Duration; -use std::sync::Arc; -use std::sync::atomic::{Ordering, AtomicBool}; struct Pending(Rc<()>); @@ -52,9 +52,14 @@ fn run_until_executes_spawned() { let (tx, rx) = oneshot::channel(); let mut pool = LocalPool::new(); let spawn = pool.spawner(); - spawn.spawn_local_obj(Box::pin(lazy(move |_| { - tx.send(()).unwrap(); - })).into()).unwrap(); + spawn + .spawn_local_obj( + Box::pin(lazy(move |_| { + tx.send(()).unwrap(); + })) + .into(), + ) + .unwrap(); pool.run_until(rx).unwrap(); } @@ -74,18 +79,27 @@ fn run_executes_spawned() { let spawn = pool.spawner(); let spawn2 = pool.spawner(); - spawn.spawn_local_obj(Box::pin(lazy(move |_| { - spawn2.spawn_local_obj(Box::pin(lazy(move |_| { - cnt2.set(cnt2.get() + 1); - })).into()).unwrap(); - })).into()).unwrap(); + spawn + .spawn_local_obj( + Box::pin(lazy(move |_| { + spawn2 + .spawn_local_obj( + Box::pin(lazy(move |_| { + cnt2.set(cnt2.get() + 1); + })) + .into(), + ) + .unwrap(); + })) + .into(), + ) + .unwrap(); pool.run(); assert_eq!(cnt.get(), 1); } - #[test] fn run_spawn_many() { const ITER: usize = 200; @@ -97,9 +111,14 @@ fn run_spawn_many() { for _ in 0..ITER { let cnt = cnt.clone(); - spawn.spawn_local_obj(Box::pin(lazy(move |_| { - cnt.set(cnt.get() + 1); - })).into()).unwrap(); + spawn + .spawn_local_obj( + Box::pin(lazy(move |_| { + cnt.set(cnt.get() + 1); + })) + .into(), + ) + .unwrap(); } pool.run(); @@ -126,9 +145,14 @@ fn try_run_one_executes_one_ready() { spawn.spawn_local_obj(Box::pin(pending()).into()).unwrap(); let cnt = cnt.clone(); - spawn.spawn_local_obj(Box::pin(lazy(move |_| { - cnt.set(cnt.get() + 1); - })).into()).unwrap(); + spawn + .spawn_local_obj( + Box::pin(lazy(move |_| { + cnt.set(cnt.get() + 1); + })) + .into(), + ) + .unwrap(); spawn.spawn_local_obj(Box::pin(pending()).into()).unwrap(); } @@ -154,15 +178,20 @@ fn try_run_one_returns_on_no_progress() { { let cnt = cnt.clone(); let waker = waker.clone(); - spawn.spawn_local_obj(Box::pin(poll_fn(move |ctx| { - cnt.set(cnt.get() + 1); - waker.set(Some(ctx.waker().clone())); - if cnt.get() == ITER { - Poll::Ready(()) - } else { - Poll::Pending - } - })).into()).unwrap(); + spawn + .spawn_local_obj( + Box::pin(poll_fn(move |ctx| { + cnt.set(cnt.get() + 1); + waker.set(Some(ctx.waker().clone())); + if cnt.get() == ITER { + Poll::Ready(()) + } else { + Poll::Pending + } + })) + .into(), + ) + .unwrap(); } for i in 0..ITER - 1 { @@ -185,16 +214,21 @@ fn try_run_one_runs_sub_futures() { let inner_spawner = spawn.clone(); let cnt1 = cnt.clone(); - spawn.spawn_local_obj(Box::pin(poll_fn(move |_| { - cnt1.set(cnt1.get() + 1); - - let cnt2 = cnt1.clone(); - inner_spawner.spawn_local_obj(Box::pin(lazy(move |_|{ - cnt2.set(cnt2.get() + 1) - })).into()).unwrap(); + spawn + .spawn_local_obj( + Box::pin(poll_fn(move |_| { + cnt1.set(cnt1.get() + 1); - Poll::Pending - })).into()).unwrap(); + let cnt2 = cnt1.clone(); + inner_spawner + .spawn_local_obj(Box::pin(lazy(move |_| cnt2.set(cnt2.get() + 1))).into()) + .unwrap(); + + Poll::Pending + })) + .into(), + ) + .unwrap(); pool.try_run_one(); assert_eq!(cnt.get(), 2); @@ -214,12 +248,12 @@ fn run_until_stalled_returns_multiple_times() { let cnt = Rc::new(Cell::new(0)); let cnt1 = cnt.clone(); - spawn.spawn_local_obj(Box::pin(lazy(move |_|{ cnt1.set(cnt1.get() + 1) })).into()).unwrap(); + spawn.spawn_local_obj(Box::pin(lazy(move |_| cnt1.set(cnt1.get() + 1))).into()).unwrap(); pool.run_until_stalled(); assert_eq!(cnt.get(), 1); let cnt2 = cnt.clone(); - spawn.spawn_local_obj(Box::pin(lazy(move |_|{ cnt2.set(cnt2.get() + 1) })).into()).unwrap(); + spawn.spawn_local_obj(Box::pin(lazy(move |_| cnt2.set(cnt2.get() + 1))).into()).unwrap(); pool.run_until_stalled(); assert_eq!(cnt.get(), 2); } @@ -232,16 +266,21 @@ fn run_until_stalled_runs_spawned_sub_futures() { let inner_spawner = spawn.clone(); let cnt1 = cnt.clone(); - spawn.spawn_local_obj(Box::pin(poll_fn(move |_| { - cnt1.set(cnt1.get() + 1); - - let cnt2 = cnt1.clone(); - inner_spawner.spawn_local_obj(Box::pin(lazy(move |_|{ - cnt2.set(cnt2.get() + 1) - })).into()).unwrap(); + spawn + .spawn_local_obj( + Box::pin(poll_fn(move |_| { + cnt1.set(cnt1.get() + 1); - Poll::Pending - })).into()).unwrap(); + let cnt2 = cnt1.clone(); + inner_spawner + .spawn_local_obj(Box::pin(lazy(move |_| cnt2.set(cnt2.get() + 1))).into()) + .unwrap(); + + Poll::Pending + })) + .into(), + ) + .unwrap(); pool.run_until_stalled(); assert_eq!(cnt.get(), 2); @@ -262,9 +301,14 @@ fn run_until_stalled_executes_all_ready() { spawn.spawn_local_obj(Box::pin(pending()).into()).unwrap(); let cnt = cnt.clone(); - spawn.spawn_local_obj(Box::pin(lazy(move |_| { - cnt.set(cnt.get() + 1); - })).into()).unwrap(); + spawn + .spawn_local_obj( + Box::pin(lazy(move |_| { + cnt.set(cnt.get() + 1); + })) + .into(), + ) + .unwrap(); // also add some pending tasks to test if they are ignored spawn.spawn_local_obj(Box::pin(pending()).into()).unwrap(); @@ -281,10 +325,15 @@ fn nesting_run() { let mut pool = LocalPool::new(); let spawn = pool.spawner(); - spawn.spawn_obj(Box::pin(lazy(|_| { - let mut pool = LocalPool::new(); - pool.run(); - })).into()).unwrap(); + spawn + .spawn_obj( + Box::pin(lazy(|_| { + let mut pool = LocalPool::new(); + pool.run(); + })) + .into(), + ) + .unwrap(); pool.run(); } @@ -295,10 +344,15 @@ fn nesting_run_run_until_stalled() { let mut pool = LocalPool::new(); let spawn = pool.spawner(); - spawn.spawn_obj(Box::pin(lazy(|_| { - let mut pool = LocalPool::new(); - pool.run_until_stalled(); - })).into()).unwrap(); + spawn + .spawn_obj( + Box::pin(lazy(|_| { + let mut pool = LocalPool::new(); + pool.run_until_stalled(); + })) + .into(), + ) + .unwrap(); pool.run(); } @@ -342,15 +396,9 @@ fn tasks_are_scheduled_fairly() { let mut pool = LocalPool::new(); let spawn = pool.spawner(); - spawn.spawn_local_obj(Box::pin(Spin { - state: state.clone(), - idx: 0, - }).into()).unwrap(); + spawn.spawn_local_obj(Box::pin(Spin { state: state.clone(), idx: 0 }).into()).unwrap(); - spawn.spawn_local_obj(Box::pin(Spin { - state, - idx: 1, - }).into()).unwrap(); + spawn.spawn_local_obj(Box::pin(Spin { state, idx: 1 }).into()).unwrap(); pool.run(); } @@ -363,11 +411,11 @@ fn park_unpark_independence() { let future = future::poll_fn(move |cx| { if done { - return Poll::Ready(()) + return Poll::Ready(()); } done = true; cx.waker().clone().wake(); // (*) - // some user-code that temporarily parks the thread + // some user-code that temporarily parks the thread let test = thread::current(); let latch = Arc::new(AtomicBool::new(false)); let signal = latch.clone(); @@ -384,4 +432,3 @@ fn park_unpark_independence() { futures::executor::block_on(future) } - diff --git a/futures-io/src/lib.rs b/futures-io/src/lib.rs index c1c64d86da..cfa1ed5ad8 100644 --- a/futures-io/src/lib.rs +++ b/futures-io/src/lib.rs @@ -9,16 +9,12 @@ //! library is activated, and it is activated by default. #![cfg_attr(all(feature = "read-initializer", feature = "std"), feature(read_initializer))] - #![cfg_attr(not(feature = "std"), no_std)] - #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms, unreachable_pub)] // It cannot be included in the published code because this lints have false positives in the minimum required version. #![cfg_attr(test, warn(single_use_lifetimes))] #![warn(clippy::all)] - #![doc(test(attr(deny(warnings), allow(dead_code, unused_assignments, unused_variables))))] - #![doc(html_root_url = "https://docs.rs/futures-io/0.3.0")] #[cfg(all(feature = "read-initializer", not(feature = "unstable")))] @@ -34,18 +30,11 @@ mod if_std { // Re-export some types from `std::io` so that users don't have to deal // with conflicts when `use`ing `futures::io` and `std::io`. #[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411 - pub use io::{ - Error as Error, - ErrorKind as ErrorKind, - Result as Result, - IoSlice as IoSlice, - IoSliceMut as IoSliceMut, - SeekFrom as SeekFrom, - }; + pub use io::{Error, ErrorKind, IoSlice, IoSliceMut, Result, SeekFrom}; #[cfg(feature = "read-initializer")] #[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411 - pub use io::Initializer as Initializer; + pub use io::Initializer; /// Read bytes asynchronously. /// @@ -90,8 +79,11 @@ mod if_std { /// `Interrupted`. Implementations must convert `WouldBlock` into /// `Poll::Pending` and either internally retry or convert /// `Interrupted` into another error kind. - fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) - -> Poll>; + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut [u8], + ) -> Poll>; /// Attempt to read from the `AsyncRead` into `bufs` using vectored /// IO operations. @@ -115,9 +107,11 @@ mod if_std { /// `Interrupted`. Implementations must convert `WouldBlock` into /// `Poll::Pending` and either internally retry or convert /// `Interrupted` into another error kind. - fn poll_read_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>]) - -> Poll> - { + fn poll_read_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &mut [IoSliceMut<'_>], + ) -> Poll> { for b in bufs { if !b.is_empty() { return self.poll_read(cx, b); @@ -154,8 +148,11 @@ mod if_std { /// /// `poll_write` must try to make progress by flushing the underlying object if /// that is the only way the underlying object can become writable again. - fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) - -> Poll>; + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll>; /// Attempt to write bytes from `bufs` into the object using vectored /// IO operations. @@ -180,9 +177,11 @@ mod if_std { /// `Interrupted`. Implementations must convert `WouldBlock` into /// `Poll::Pending` and either internally retry or convert /// `Interrupted` into another error kind. - fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>]) - -> Poll> - { + fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], + ) -> Poll> { for b in bufs { if !b.is_empty() { return self.poll_write(cx, b); @@ -257,8 +256,11 @@ mod if_std { /// `Interrupted`. Implementations must convert `WouldBlock` into /// `Poll::Pending` and either internally retry or convert /// `Interrupted` into another error kind. - fn poll_seek(self: Pin<&mut Self>, cx: &mut Context<'_>, pos: SeekFrom) - -> Poll>; + fn poll_seek( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + pos: SeekFrom, + ) -> Poll>; } /// Read bytes asynchronously. @@ -297,8 +299,7 @@ mod if_std { /// `Interrupted`. Implementations must convert `WouldBlock` into /// `Poll::Pending` and either internally retry or convert /// `Interrupted` into another error kind. - fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) - -> Poll>; + fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll>; /// Tells this buffer that `amt` bytes have been consumed from the buffer, /// so they should no longer be returned in calls to [`poll_read`]. @@ -325,18 +326,22 @@ mod if_std { (**self).initializer() } - fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) - -> Poll> - { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut [u8], + ) -> Poll> { Pin::new(&mut **self).poll_read(cx, buf) } - fn poll_read_vectored(mut self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>]) - -> Poll> - { + fn poll_read_vectored( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &mut [IoSliceMut<'_>], + ) -> Poll> { Pin::new(&mut **self).poll_read_vectored(cx, bufs) } - } + }; } impl AsyncRead for Box { @@ -357,15 +362,19 @@ mod if_std { (**self).initializer() } - fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) - -> Poll> - { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut [u8], + ) -> Poll> { self.get_mut().as_mut().poll_read(cx, buf) } - fn poll_read_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>]) - -> Poll> - { + fn poll_read_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &mut [IoSliceMut<'_>], + ) -> Poll> { self.get_mut().as_mut().poll_read_vectored(cx, bufs) } } @@ -377,18 +386,22 @@ mod if_std { io::Read::initializer(self) } - fn poll_read(mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &mut [u8]) - -> Poll> - { + fn poll_read( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + buf: &mut [u8], + ) -> Poll> { Poll::Ready(io::Read::read(&mut *self, buf)) } - fn poll_read_vectored(mut self: Pin<&mut Self>, _: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>]) - -> Poll> - { + fn poll_read_vectored( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + bufs: &mut [IoSliceMut<'_>], + ) -> Poll> { Poll::Ready(io::Read::read_vectored(&mut *self, bufs)) } - } + }; } impl AsyncRead for &[u8] { @@ -397,15 +410,19 @@ mod if_std { macro_rules! deref_async_write { () => { - fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) - -> Poll> - { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { Pin::new(&mut **self).poll_write(cx, buf) } - fn poll_write_vectored(mut self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>]) - -> Poll> - { + fn poll_write_vectored( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], + ) -> Poll> { Pin::new(&mut **self).poll_write_vectored(cx, bufs) } @@ -416,7 +433,7 @@ mod if_std { fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { Pin::new(&mut **self).poll_close(cx) } - } + }; } impl AsyncWrite for Box { @@ -432,15 +449,19 @@ mod if_std { P: DerefMut + Unpin, P::Target: AsyncWrite, { - fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) - -> Poll> - { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { self.get_mut().as_mut().poll_write(cx, buf) } - fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>]) - -> Poll> - { + fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], + ) -> Poll> { self.get_mut().as_mut().poll_write_vectored(cx, bufs) } @@ -455,15 +476,19 @@ mod if_std { macro_rules! delegate_async_write_to_stdio { () => { - fn poll_write(mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &[u8]) - -> Poll> - { + fn poll_write( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { Poll::Ready(io::Write::write(&mut *self, buf)) } - fn poll_write_vectored(mut self: Pin<&mut Self>, _: &mut Context<'_>, bufs: &[IoSlice<'_>]) - -> Poll> - { + fn poll_write_vectored( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + bufs: &[IoSlice<'_>], + ) -> Poll> { Poll::Ready(io::Write::write_vectored(&mut *self, bufs)) } @@ -474,7 +499,7 @@ mod if_std { fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.poll_flush(cx) } - } + }; } impl AsyncWrite for Vec { @@ -483,12 +508,14 @@ mod if_std { macro_rules! deref_async_seek { () => { - fn poll_seek(mut self: Pin<&mut Self>, cx: &mut Context<'_>, pos: SeekFrom) - -> Poll> - { + fn poll_seek( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + pos: SeekFrom, + ) -> Poll> { Pin::new(&mut **self).poll_seek(cx, pos) } - } + }; } impl AsyncSeek for Box { @@ -504,25 +531,25 @@ mod if_std { P: DerefMut + Unpin, P::Target: AsyncSeek, { - fn poll_seek(self: Pin<&mut Self>, cx: &mut Context<'_>, pos: SeekFrom) - -> Poll> - { + fn poll_seek( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + pos: SeekFrom, + ) -> Poll> { self.get_mut().as_mut().poll_seek(cx, pos) } } macro_rules! deref_async_buf_read { () => { - fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) - -> Poll> - { + fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { Pin::new(&mut **self.get_mut()).poll_fill_buf(cx) } fn consume(mut self: Pin<&mut Self>, amt: usize) { Pin::new(&mut **self).consume(amt) } - } + }; } impl AsyncBufRead for Box { @@ -538,9 +565,7 @@ mod if_std { P: DerefMut + Unpin, P::Target: AsyncBufRead, { - fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) - -> Poll> - { + fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.get_mut().as_mut().poll_fill_buf(cx) } @@ -551,16 +576,14 @@ mod if_std { macro_rules! delegate_async_buf_read_to_stdio { () => { - fn poll_fill_buf(self: Pin<&mut Self>, _: &mut Context<'_>) - -> Poll> - { + fn poll_fill_buf(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { Poll::Ready(io::BufRead::fill_buf(self.get_mut())) } fn consume(self: Pin<&mut Self>, amt: usize) { io::BufRead::consume(self.get_mut(), amt) } - } + }; } impl AsyncBufRead for &[u8] { diff --git a/futures-macro/src/join.rs b/futures-macro/src/join.rs index 2a7b11ca6b..6170622689 100644 --- a/futures-macro/src/join.rs +++ b/futures-macro/src/join.rs @@ -69,9 +69,7 @@ fn bind_futures( pub(crate) fn join(input: TokenStream) -> TokenStream { let parsed = syn::parse_macro_input!(input as Join); - let futures_crate = parsed - .futures_crate_path - .unwrap_or_else(|| parse_quote!(::futures_util)); + let futures_crate = parsed.futures_crate_path.unwrap_or_else(|| parse_quote!(::futures_util)); // should be def_site, but that's unstable let span = Span::call_site(); @@ -111,9 +109,7 @@ pub(crate) fn join(input: TokenStream) -> TokenStream { pub(crate) fn try_join(input: TokenStream) -> TokenStream { let parsed = syn::parse_macro_input!(input as Join); - let futures_crate = parsed - .futures_crate_path - .unwrap_or_else(|| parse_quote!(::futures_util)); + let futures_crate = parsed.futures_crate_path.unwrap_or_else(|| parse_quote!(::futures_util)); // should be def_site, but that's unstable let span = Span::call_site(); diff --git a/futures-macro/src/lib.rs b/futures-macro/src/lib.rs index 932ec2e4f1..111973bed1 100644 --- a/futures-macro/src/lib.rs +++ b/futures-macro/src/lib.rs @@ -5,9 +5,7 @@ // It cannot be included in the published code because this lints have false positives in the minimum required version. #![cfg_attr(test, warn(single_use_lifetimes))] #![warn(clippy::all)] - #![doc(test(attr(deny(warnings), allow(dead_code, unused_assignments, unused_variables))))] - #![doc(html_root_url = "https://docs.rs/futures-join-macro/0.3.0")] // Since https://github.com/rust-lang/cargo/pull/7700 `proc_macro` is part of the prelude for diff --git a/futures-macro/src/select.rs b/futures-macro/src/select.rs index f7f688b6ae..a8f84cb13d 100644 --- a/futures-macro/src/select.rs +++ b/futures-macro/src/select.rs @@ -3,8 +3,8 @@ use proc_macro::TokenStream; use proc_macro2::Span; use quote::{format_ident, quote}; -use syn::{parenthesized, parse_quote, Expr, Ident, Pat, Token}; use syn::parse::{Parse, ParseStream}; +use syn::{parenthesized, parse_quote, Expr, Ident, Pat, Token}; mod kw { syn::custom_keyword!(complete); @@ -76,7 +76,10 @@ impl Parse for Select { // Commas after the expression are only optional if it's a `Block` // or it is the last branch in the `match`. - let is_block = match expr { Expr::Block(_) => true, _ => false }; + let is_block = match expr { + Expr::Block(_) => true, + _ => false, + }; if is_block || input.is_empty() { input.parse::>()?; } else { @@ -89,7 +92,7 @@ impl Parse for Select { CaseKind::Normal(pat, fut_expr) => { select.normal_fut_exprs.push(fut_expr); select.normal_fut_handlers.push((pat, expr)); - }, + } } } @@ -105,22 +108,16 @@ fn declare_result_enum( result_ident: Ident, variants: usize, complete: bool, - span: Span + span: Span, ) -> (Vec, syn::ItemEnum) { // "_0", "_1", "_2" let variant_names: Vec = - (0..variants) - .map(|num| format_ident!("_{}", num, span = span)) - .collect(); + (0..variants).map(|num| format_ident!("_{}", num, span = span)).collect(); let type_parameters = &variant_names; let variants = &variant_names; - let complete_variant = if complete { - Some(quote!(Complete)) - } else { - None - }; + let complete_variant = if complete { Some(quote!(Complete)) } else { None }; let enum_item = parse_quote! { enum #result_ident<#(#type_parameters,)*> { @@ -147,7 +144,8 @@ pub(crate) fn select_biased(input: TokenStream) -> TokenStream { fn select_inner(input: TokenStream, random: bool) -> TokenStream { let parsed = syn::parse_macro_input!(input as Select); - let futures_crate: syn::Path = parsed.futures_crate_path.unwrap_or_else(|| parse_quote!(::futures_util)); + let futures_crate: syn::Path = + parsed.futures_crate_path.unwrap_or_else(|| parse_quote!(::futures_util)); // should be def_site, but that's unstable let span = Span::call_site(); @@ -163,7 +161,9 @@ fn select_inner(input: TokenStream, random: bool) -> TokenStream { // bind non-`Ident` future exprs w/ `let` let mut future_let_bindings = Vec::with_capacity(parsed.normal_fut_exprs.len()); - let bound_future_names: Vec<_> = parsed.normal_fut_exprs.into_iter() + let bound_future_names: Vec<_> = parsed + .normal_fut_exprs + .into_iter() .zip(variant_names.iter()) .map(|(expr, variant_name)| { match expr { @@ -179,7 +179,7 @@ fn select_inner(input: TokenStream, random: bool) -> TokenStream { #futures_crate::async_await::assert_unpin(&#path); }); path - }, + } _ => { // Bind and pin the resulting Future on the stack. This is // necessary to support direct select! calls on !Unpin @@ -203,8 +203,8 @@ fn select_inner(input: TokenStream, random: bool) -> TokenStream { // For each future, make an `&mut dyn FnMut(&mut Context<'_>) -> Option>` // to use for polling that individual future. These will then be put in an array. - let poll_functions = bound_future_names.iter().zip(variant_names.iter()) - .map(|(bound_future_name, variant_name)| { + let poll_functions = bound_future_names.iter().zip(variant_names.iter()).map( + |(bound_future_name, variant_name)| { // Below we lazily create the Pin on the Future below. // This is done in order to avoid allocating memory in the generator // for the Pin variable. @@ -231,7 +231,8 @@ fn select_inner(input: TokenStream, random: bool) -> TokenStream { &mut #futures_crate::task::Context<'_> ) -> Option<#futures_crate::task::Poll<_>> = &mut #variant_name; } - }); + }, + ); let none_polled = if parsed.complete.is_some() { quote! { @@ -244,13 +245,13 @@ fn select_inner(input: TokenStream, random: bool) -> TokenStream { } }; - let branches = parsed.normal_fut_handlers.into_iter() - .zip(variant_names.iter()) - .map(|((pat, expr), variant_name)| { + let branches = parsed.normal_fut_handlers.into_iter().zip(variant_names.iter()).map( + |((pat, expr), variant_name)| { quote! { #enum_ident::#variant_name(#pat) => { #expr }, } - }); + }, + ); let branches = quote! { #( #branches )* }; let complete_branch = parsed.complete.map(|complete_expr| { diff --git a/futures-sink/src/lib.rs b/futures-sink/src/lib.rs index fea98fac97..45c02d9237 100644 --- a/futures-sink/src/lib.rs +++ b/futures-sink/src/lib.rs @@ -8,9 +8,7 @@ // It cannot be included in the published code because this lints have false positives in the minimum required version. #![cfg_attr(test, warn(single_use_lifetimes))] #![warn(clippy::all)] - #![doc(test(attr(deny(warnings), allow(dead_code, unused_assignments, unused_variables))))] - #![doc(html_root_url = "https://docs.rs/futures-sink/0.3.0")] #[cfg(feature = "alloc")] @@ -210,7 +208,10 @@ mod if_alloc { impl + Unpin, Item> Sink for alloc::boxed::Box { type Error = S::Error; - fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + fn poll_ready( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll> { Pin::new(&mut **self).poll_ready(cx) } @@ -218,11 +219,17 @@ mod if_alloc { Pin::new(&mut **self).start_send(item) } - fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + fn poll_flush( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll> { Pin::new(&mut **self).poll_flush(cx) } - fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + fn poll_close( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll> { Pin::new(&mut **self).poll_close(cx) } } diff --git a/futures-task/src/future_obj.rs b/futures-task/src/future_obj.rs index 6acdf7c37f..578eb58c03 100644 --- a/futures-task/src/future_obj.rs +++ b/futures-task/src/future_obj.rs @@ -1,8 +1,8 @@ use core::{ - mem, fmt, future::Future, marker::PhantomData, + mem, pin::Pin, task::{Context, Poll}, }; @@ -26,16 +26,16 @@ impl Unpin for LocalFutureObj<'_, T> {} #[allow(single_use_lifetimes)] #[allow(clippy::transmute_ptr_to_ptr)] -unsafe fn remove_future_lifetime<'a, T>(ptr: *mut (dyn Future + 'a)) - -> *mut (dyn Future + 'static) -{ +unsafe fn remove_future_lifetime<'a, T>( + ptr: *mut (dyn Future + 'a), +) -> *mut (dyn Future + 'static) { mem::transmute(ptr) } #[allow(single_use_lifetimes)] -unsafe fn remove_drop_lifetime<'a, T>(ptr: unsafe fn (*mut (dyn Future + 'a))) - -> unsafe fn(*mut (dyn Future + 'static)) -{ +unsafe fn remove_drop_lifetime<'a, T>( + ptr: unsafe fn(*mut (dyn Future + 'a)), +) -> unsafe fn(*mut (dyn Future + 'static)) { mem::transmute(ptr) } @@ -65,8 +65,7 @@ impl<'a, T> LocalFutureObj<'a, T> { impl fmt::Debug for LocalFutureObj<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("LocalFutureObj") - .finish() + f.debug_struct("LocalFutureObj").finish() } } @@ -82,17 +81,13 @@ impl Future for LocalFutureObj<'_, T> { #[inline] fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - unsafe { - Pin::new_unchecked(&mut *self.future).poll(cx) - } + unsafe { Pin::new_unchecked(&mut *self.future).poll(cx) } } } impl Drop for LocalFutureObj<'_, T> { fn drop(&mut self) { - unsafe { - (self.drop_fn)(self.future) - } + unsafe { (self.drop_fn)(self.future) } } } @@ -120,8 +115,7 @@ impl<'a, T> FutureObj<'a, T> { impl fmt::Debug for FutureObj<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("FutureObj") - .finish() + f.debug_struct("FutureObj").finish() } } @@ -130,7 +124,7 @@ impl Future for FutureObj<'_, T> { #[inline] fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - Pin::new( &mut self.0 ).poll(cx) + Pin::new(&mut self.0).poll(cx) } } @@ -180,7 +174,7 @@ pub unsafe trait UnsafeFutureObj<'a, T>: 'a { unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for &'a mut F where - F: Future + Unpin + 'a + F: Future + Unpin + 'a, { fn into_raw(self) -> *mut (dyn Future + 'a) { self as *mut dyn Future @@ -189,8 +183,7 @@ where unsafe fn drop(_ptr: *mut (dyn Future + 'a)) {} } -unsafe impl<'a, T> UnsafeFutureObj<'a, T> for &'a mut (dyn Future + Unpin + 'a) -{ +unsafe impl<'a, T> UnsafeFutureObj<'a, T> for &'a mut (dyn Future + Unpin + 'a) { fn into_raw(self) -> *mut (dyn Future + 'a) { self as *mut dyn Future } @@ -200,7 +193,7 @@ unsafe impl<'a, T> UnsafeFutureObj<'a, T> for &'a mut (dyn Future + unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for Pin<&'a mut F> where - F: Future + 'a + F: Future + 'a, { fn into_raw(self) -> *mut (dyn Future + 'a) { unsafe { self.get_unchecked_mut() as *mut dyn Future } @@ -209,8 +202,7 @@ where unsafe fn drop(_ptr: *mut (dyn Future + 'a)) {} } -unsafe impl<'a, T> UnsafeFutureObj<'a, T> for Pin<&'a mut (dyn Future + 'a)> -{ +unsafe impl<'a, T> UnsafeFutureObj<'a, T> for Pin<&'a mut (dyn Future + 'a)> { fn into_raw(self) -> *mut (dyn Future + 'a) { unsafe { self.get_unchecked_mut() as *mut dyn Future } } @@ -224,7 +216,8 @@ mod if_alloc { use alloc::boxed::Box; unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for Box - where F: Future + 'a + where + F: Future + 'a, { fn into_raw(self) -> *mut (dyn Future + 'a) { Box::into_raw(self) @@ -257,7 +250,7 @@ mod if_alloc { unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for Pin> where - F: Future + 'a + F: Future + 'a, { fn into_raw(mut self) -> *mut (dyn Future + 'a) { let ptr = unsafe { self.as_mut().get_unchecked_mut() as *mut _ }; diff --git a/futures-task/src/lib.rs b/futures-task/src/lib.rs index b18a33a83f..42c1d24f8a 100644 --- a/futures-task/src/lib.rs +++ b/futures-task/src/lib.rs @@ -1,16 +1,12 @@ //! Tools for working with tasks. #![cfg_attr(feature = "cfg-target-has-atomic", feature(cfg_target_has_atomic))] - #![cfg_attr(not(feature = "std"), no_std)] - #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms, unreachable_pub)] // It cannot be included in the published code because this lints have false positives in the minimum required version. #![cfg_attr(test, warn(single_use_lifetimes))] #![warn(clippy::all)] - #![doc(test(attr(deny(warnings), allow(dead_code, unused_assignments, unused_variables))))] - #![doc(html_root_url = "https://docs.rs/futures-task/0.3.0")] #[cfg(all(feature = "cfg-target-has-atomic", not(feature = "unstable")))] @@ -27,7 +23,7 @@ macro_rules! cfg_target_has_atomic { } mod spawn; -pub use crate::spawn::{Spawn, SpawnError, LocalSpawn}; +pub use crate::spawn::{LocalSpawn, Spawn, SpawnError}; cfg_target_has_atomic! { #[cfg(feature = "alloc")] @@ -54,4 +50,4 @@ pub use crate::noop_waker::noop_waker; #[cfg(feature = "std")] pub use crate::noop_waker::noop_waker_ref; -pub use core::task::{Context, Poll, Waker, RawWaker, RawWakerVTable}; +pub use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker}; diff --git a/futures-task/src/noop_waker.rs b/futures-task/src/noop_waker.rs index a0924ad925..6f3e7bd51d 100644 --- a/futures-task/src/noop_waker.rs +++ b/futures-task/src/noop_waker.rs @@ -1,9 +1,9 @@ //! Utilities for creating zero-cost wakers that don't do anything. -use core::task::{RawWaker, RawWakerVTable, Waker}; -use core::ptr::null; #[cfg(feature = "std")] use core::cell::UnsafeCell; +use core::ptr::null; +use core::task::{RawWaker, RawWakerVTable, Waker}; unsafe fn noop_clone(_data: *const ()) -> RawWaker { noop_raw_waker() @@ -29,9 +29,7 @@ fn noop_raw_waker() -> RawWaker { /// ``` #[inline] pub fn noop_waker() -> Waker { - unsafe { - Waker::from_raw(noop_raw_waker()) - } + unsafe { Waker::from_raw(noop_raw_waker()) } } /// Get a static reference to a [`Waker`] which diff --git a/futures-task/src/spawn.rs b/futures-task/src/spawn.rs index a515dd4e18..50f5d0d56a 100644 --- a/futures-task/src/spawn.rs +++ b/futures-task/src/spawn.rs @@ -126,7 +126,7 @@ impl LocalSpawn for &mut Sp { #[cfg(feature = "alloc")] mod if_alloc { use super::*; - use alloc::{ boxed::Box, rc::Rc }; + use alloc::{boxed::Box, rc::Rc}; impl Spawn for Box { fn spawn_obj(&self, future: FutureObj<'static, ()>) -> Result<(), SpawnError> { diff --git a/futures-test/src/assert.rs b/futures-test/src/assert.rs index 24b4ec8e75..c7aa3c8163 100644 --- a/futures-test/src/assert.rs +++ b/futures-test/src/assert.rs @@ -30,9 +30,7 @@ macro_rules! assert_stream_pending { $crate::assert::assert_is_unpin_stream(stream); let stream = $crate::std_reexport::pin::Pin::new(stream); let mut cx = $crate::task::noop_context(); - let poll = $crate::futures_core_reexport::stream::Stream::poll_next( - stream, &mut cx, - ); + let poll = $crate::futures_core_reexport::stream::Stream::poll_next(stream, &mut cx); if poll.is_ready() { panic!("assertion failed: stream is not pending"); } @@ -71,13 +69,15 @@ macro_rules! assert_stream_next { assert_eq!(x, $item); } $crate::futures_core_reexport::task::Poll::Ready(None) => { - panic!("assertion failed: expected stream to provide item but stream is at its end"); + panic!( + "assertion failed: expected stream to provide item but stream is at its end" + ); } $crate::futures_core_reexport::task::Poll::Pending => { panic!("assertion failed: expected stream to provide item but stream wasn't ready"); } } - }} + }}; } /// Assert that the next poll to the provided stream will return an empty @@ -117,5 +117,5 @@ macro_rules! assert_stream_done { panic!("assertion failed: expected stream to be done but was pending"); } } - }} + }}; } diff --git a/futures-test/src/future/assert_unmoved.rs b/futures-test/src/future/assert_unmoved.rs index 74f92c626b..d33fb75aa9 100644 --- a/futures-test/src/future/assert_unmoved.rs +++ b/futures-test/src/future/assert_unmoved.rs @@ -22,21 +22,14 @@ impl AssertUnmoved { unsafe_unpinned!(this_ptr: *const Self); pub(super) fn new(future: Fut) -> Self { - Self { - future, - this_ptr: ptr::null(), - _pinned: PhantomPinned, - } + Self { future, this_ptr: ptr::null(), _pinned: PhantomPinned } } } impl Future for AssertUnmoved { type Output = Fut::Output; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let cur_this = &*self as *const Self; if self.this_ptr.is_null() { // First time being polled diff --git a/futures-test/src/future/pending_once.rs b/futures-test/src/future/pending_once.rs index f803f3a543..7454b244a2 100644 --- a/futures-test/src/future/pending_once.rs +++ b/futures-test/src/future/pending_once.rs @@ -1,7 +1,7 @@ -use futures_core::future::{Future, FusedFuture}; +use futures_core::future::{FusedFuture, Future}; use futures_core::task::{Context, Poll}; -use std::pin::Pin; use pin_utils::{unsafe_pinned, unsafe_unpinned}; +use std::pin::Pin; /// Combinator that guarantees one [`Poll::Pending`] before polling its inner /// future. @@ -21,20 +21,14 @@ impl PendingOnce { unsafe_unpinned!(polled_before: bool); pub(super) fn new(future: Fut) -> Self { - Self { - future, - polled_before: false, - } + Self { future, polled_before: false } } } impl Future for PendingOnce { type Output = Fut::Output; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { if self.polled_before { self.as_mut().future().poll(cx) } else { diff --git a/futures-test/src/interleave_pending.rs b/futures-test/src/interleave_pending.rs index 35c599dcdb..a847243613 100644 --- a/futures-test/src/interleave_pending.rs +++ b/futures-test/src/interleave_pending.rs @@ -1,5 +1,5 @@ -use futures_core::future::{Future, FusedFuture}; -use futures_core::stream::{Stream, FusedStream}; +use futures_core::future::{FusedFuture, Future}; +use futures_core::stream::{FusedStream, Stream}; use futures_io::{self as io, AsyncBufRead, AsyncRead, AsyncWrite}; use pin_utils::{unsafe_pinned, unsafe_unpinned}; use std::{ @@ -27,10 +27,7 @@ impl InterleavePending { unsafe_unpinned!(pended: bool); pub(crate) fn new(inner: T) -> Self { - Self { - inner, - pended: false, - } + Self { inner, pended: false } } /// Acquires a reference to the underlying I/O object that this adaptor is @@ -67,10 +64,7 @@ impl InterleavePending { impl Future for InterleavePending { type Output = Fut::Output; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { if *self.as_mut().pended() { let next = self.as_mut().inner().poll(cx); if next.is_ready() { @@ -94,10 +88,7 @@ impl FusedFuture for InterleavePending { impl Stream for InterleavePending { type Item = St::Item; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if *self.as_mut().pended() { let next = self.as_mut().inner().poll_next(cx); if next.is_ready() { @@ -142,10 +133,7 @@ impl AsyncWrite for InterleavePending { } } - fn poll_flush( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let (writer, pended) = self.project(); if *pended { let next = writer.poll_flush(cx); @@ -160,10 +148,7 @@ impl AsyncWrite for InterleavePending { } } - fn poll_close( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let (writer, pended) = self.project(); if *pended { let next = writer.poll_close(cx); @@ -201,10 +186,7 @@ impl AsyncRead for InterleavePending { } impl AsyncBufRead for InterleavePending { - fn poll_fill_buf( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let (reader, pended) = self.project(); if *pended { let next = reader.poll_fill_buf(cx); diff --git a/futures-test/src/io/limited.rs b/futures-test/src/io/limited.rs index 68ba674d4d..09a4e9f7b3 100644 --- a/futures-test/src/io/limited.rs +++ b/futures-test/src/io/limited.rs @@ -62,17 +62,11 @@ impl AsyncWrite for Limited { self.io().poll_write(cx, &buf[..cmp::min(limit, buf.len())]) } - fn poll_flush( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.io().poll_flush(cx) } - fn poll_close( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.io().poll_close(cx) } } @@ -89,10 +83,7 @@ impl AsyncRead for Limited { } impl AsyncBufRead for Limited { - fn poll_fill_buf( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.io().poll_fill_buf(cx) } diff --git a/futures-test/src/lib.rs b/futures-test/src/lib.rs index da018fe5b9..479320af66 100644 --- a/futures-test/src/lib.rs +++ b/futures-test/src/lib.rs @@ -4,13 +4,13 @@ // It cannot be included in the published code because this lints have false positives in the minimum required version. #![cfg_attr(test, warn(single_use_lifetimes))] #![warn(clippy::all)] - #![doc(test(attr(deny(warnings), allow(dead_code, unused_assignments, unused_variables))))] - #![doc(html_root_url = "https://docs.rs/futures-test/0.3.0")] #[cfg(not(feature = "std"))] -compile_error!("`futures-test` must have the `std` feature activated, this is a default-active feature"); +compile_error!( + "`futures-test` must have the `std` feature activated, this is a default-active feature" +); #[doc(hidden)] #[cfg(feature = "std")] diff --git a/futures-test/src/task/context.rs b/futures-test/src/task/context.rs index 602127c657..b2b0dfe31e 100644 --- a/futures-test/src/task/context.rs +++ b/futures-test/src/task/context.rs @@ -1,4 +1,4 @@ -use crate::task::{panic_waker_ref, noop_waker_ref}; +use crate::task::{noop_waker_ref, panic_waker_ref}; use futures_core::task::Context; /// Create a new [`Context`](core::task::Context) where the diff --git a/futures-test/src/task/mod.rs b/futures-test/src/task/mod.rs index 9d775dd207..d9478f6cc6 100644 --- a/futures-test/src/task/mod.rs +++ b/futures-test/src/task/mod.rs @@ -57,4 +57,4 @@ mod record_spawner; pub use self::record_spawner::RecordSpawner; mod wake_counter; -pub use self::wake_counter::{AwokenCount, new_count_waker}; +pub use self::wake_counter::{new_count_waker, AwokenCount}; diff --git a/futures-test/src/task/panic_waker.rs b/futures-test/src/task/panic_waker.rs index 74476d823f..d513eebfbf 100644 --- a/futures-test/src/task/panic_waker.rs +++ b/futures-test/src/task/panic_waker.rs @@ -1,6 +1,6 @@ -use futures_core::task::{Waker, RawWaker, RawWakerVTable}; use core::cell::UnsafeCell; use core::ptr::null; +use futures_core::task::{RawWaker, RawWakerVTable, Waker}; unsafe fn clone_panic_waker(_data: *const ()) -> RawWaker { raw_panic_waker() @@ -12,12 +12,8 @@ unsafe fn wake_panic(_data: *const ()) { panic!("should not be woken"); } -const PANIC_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new( - clone_panic_waker, - wake_panic, - wake_panic, - noop, -); +const PANIC_WAKER_VTABLE: RawWakerVTable = + RawWakerVTable::new(clone_panic_waker, wake_panic, wake_panic, noop); fn raw_panic_waker() -> RawWaker { RawWaker::new(null(), &PANIC_WAKER_VTABLE) diff --git a/futures-test/src/task/wake_counter.rs b/futures-test/src/task/wake_counter.rs index cf496c2ddb..52c63e1cc9 100644 --- a/futures-test/src/task/wake_counter.rs +++ b/futures-test/src/task/wake_counter.rs @@ -1,7 +1,7 @@ use futures_core::task::Waker; use futures_util::task::{self, ArcWake}; -use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; /// Number of times the waker was awoken. /// diff --git a/futures-util/benches/futures_unordered.rs b/futures-util/benches/futures_unordered.rs index 05e9eadb79..d5fe7a59de 100644 --- a/futures-util/benches/futures_unordered.rs +++ b/futures-util/benches/futures_unordered.rs @@ -6,7 +6,7 @@ use crate::test::Bencher; use futures::channel::oneshot; use futures::executor::block_on; use futures::future; -use futures::stream::{StreamExt, FuturesUnordered}; +use futures::stream::{FuturesUnordered, StreamExt}; use futures::task::Poll; use std::collections::VecDeque; use std::thread; @@ -34,7 +34,7 @@ fn oneshots(b: &mut Bencher) { block_on(future::poll_fn(move |cx| { loop { if let Poll::Ready(None) = rxs.poll_next_unpin(cx) { - break + break; } } Poll::Ready(()) diff --git a/futures-util/src/async_await/pending.rs b/futures-util/src/async_await/pending.rs index b143869e77..0211849885 100644 --- a/futures-util/src/async_await/pending.rs +++ b/futures-util/src/async_await/pending.rs @@ -16,7 +16,7 @@ use futures_core::task::{Context, Poll}; macro_rules! pending { () => { $crate::async_await::pending_once().await - } + }; } #[doc(hidden)] diff --git a/futures-util/src/async_await/poll.rs b/futures-util/src/async_await/poll.rs index dffa94b918..ab92b914d4 100644 --- a/futures-util/src/async_await/poll.rs +++ b/futures-util/src/async_await/poll.rs @@ -13,7 +13,7 @@ use futures_core::task::{Context, Poll}; macro_rules! poll { ($x:expr $(,)?) => { $crate::async_await::poll($x).await - } + }; } #[doc(hidden)] diff --git a/futures-util/src/compat/compat01as03.rs b/futures-util/src/compat/compat01as03.rs index 9bb00bf00c..de553c4e7e 100644 --- a/futures-util/src/compat/compat01as03.rs +++ b/futures-util/src/compat/compat01as03.rs @@ -1,18 +1,15 @@ use futures_01::executor::{ - spawn as spawn01, Notify as Notify01, NotifyHandle as NotifyHandle01, - Spawn as Spawn01, UnsafeNotify as UnsafeNotify01, -}; -use futures_01::{ - Async as Async01, Future as Future01, - Stream as Stream01, + spawn as spawn01, Notify as Notify01, NotifyHandle as NotifyHandle01, Spawn as Spawn01, + UnsafeNotify as UnsafeNotify01, }; +use futures_01::{Async as Async01, Future as Future01, Stream as Stream01}; #[cfg(feature = "sink")] use futures_01::{AsyncSink as AsyncSink01, Sink as Sink01}; -use futures_core::{task as task03, future::Future as Future03, stream::Stream as Stream03}; -use std::pin::Pin; -use std::task::Context; +use futures_core::{future::Future as Future03, stream::Stream as Stream03, task as task03}; #[cfg(feature = "sink")] use futures_sink::Sink as Sink03; +use std::pin::Pin; +use std::task::Context; #[cfg(feature = "io-compat")] #[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411 @@ -32,9 +29,7 @@ impl Compat01As03 { /// Wraps a futures 0.1 Future, Stream, AsyncRead, or AsyncWrite /// object in a futures 0.3-compatible wrapper. pub fn new(object: T) -> Compat01As03 { - Compat01As03 { - inner: spawn01(object), - } + Compat01As03 { inner: spawn01(object) } } fn in_notify(&mut self, cx: &mut Context<'_>, f: impl FnOnce(&mut T) -> R) -> R { @@ -155,10 +150,7 @@ fn poll_01_to_03(x: Result, E>) -> task03::Poll> { impl Future03 for Compat01As03 { type Output = Result; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> task03::Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> task03::Poll { poll_01_to_03(self.in_notify(cx, Future01::poll)) } } @@ -195,18 +187,10 @@ impl Unpin for Compat01As03Sink {} impl Compat01As03Sink { /// Wraps a futures 0.1 Sink object in a futures 0.3-compatible wrapper. pub fn new(inner: S) -> Compat01As03Sink { - Compat01As03Sink { - inner: spawn01(inner), - buffer: None, - close_started: false - } + Compat01As03Sink { inner: spawn01(inner), buffer: None, close_started: false } } - fn in_notify( - &mut self, - cx: &mut Context<'_>, - f: impl FnOnce(&mut S) -> R, - ) -> R { + fn in_notify(&mut self, cx: &mut Context<'_>, f: impl FnOnce(&mut S) -> R) -> R { let notify = &WakerToHandle(cx.waker()); self.inner.poll_fn_notify(notify, 0, f) } @@ -253,10 +237,7 @@ where { type Error = S::SinkError; - fn start_send( - mut self: Pin<&mut Self>, - item: SinkItem, - ) -> Result<(), Self::Error> { + fn start_send(mut self: Pin<&mut Self>, item: SinkItem) -> Result<(), Self::Error> { debug_assert!(self.buffer.is_none()); self.buffer = Some(item); Ok(()) @@ -286,9 +267,7 @@ where match self.in_notify(cx, |f| match item { Some(i) => match f.start_send(i)? { AsyncSink01::Ready => f.poll_complete().map(|i| (i, None)), - AsyncSink01::NotReady(t) => { - Ok((Async01::NotReady, Some(t))) - } + AsyncSink01::NotReady(t) => Ok((Async01::NotReady, Some(t))), }, None => f.poll_complete().map(|i| (i, None)), })? { @@ -443,29 +422,35 @@ mod io { } } - fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) - -> task03::Poll> - { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut [u8], + ) -> task03::Poll> { poll_01_to_03(self.in_notify(cx, |x| x.poll_read(buf))) } } impl AsyncWrite03 for Compat01As03 { - fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) - -> task03::Poll> - { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> task03::Poll> { poll_01_to_03(self.in_notify(cx, |x| x.poll_write(buf))) } - fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) - -> task03::Poll> - { + fn poll_flush( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> task03::Poll> { poll_01_to_03(self.in_notify(cx, AsyncWrite01::poll_flush)) } - fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) - -> task03::Poll> - { + fn poll_close( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> task03::Poll> { poll_01_to_03(self.in_notify(cx, AsyncWrite01::shutdown)) } } diff --git a/futures-util/src/compat/compat03as01.rs b/futures-util/src/compat/compat03as01.rs index 3fd2ae0616..55f2e11782 100644 --- a/futures-util/src/compat/compat03as01.rs +++ b/futures-util/src/compat/compat03as01.rs @@ -1,31 +1,19 @@ +use crate::task::{self as task03, ArcWake as ArcWake03, WakerRef}; use futures_01::{ - task as task01, Async as Async01, Future as Future01, Poll as Poll01, - Stream as Stream01, + task as task01, Async as Async01, Future as Future01, Poll as Poll01, Stream as Stream01, }; #[cfg(feature = "sink")] -use futures_01::{ - AsyncSink as AsyncSink01, Sink as Sink01, StartSend as StartSend01, -}; +use futures_01::{AsyncSink as AsyncSink01, Sink as Sink01, StartSend as StartSend01}; use futures_core::{ - task::{RawWaker, RawWakerVTable}, future::TryFuture as TryFuture03, stream::TryStream as TryStream03, + task::{RawWaker, RawWakerVTable}, }; #[cfg(feature = "sink")] use futures_sink::Sink as Sink03; -use crate::task::{ - self as task03, - ArcWake as ArcWake03, - WakerRef, -}; #[cfg(feature = "sink")] use std::marker::PhantomData; -use std::{ - mem, - pin::Pin, - sync::Arc, - task::Context, -}; +use std::{mem, pin::Pin, sync::Arc, task::Context}; /// Converts a futures 0.3 [`TryFuture`](futures_core::future::TryFuture) or /// [`TryStream`](futures_core::stream::TryStream) into a futures 0.1 @@ -79,10 +67,7 @@ impl Compat { impl CompatSink { /// Creates a new [`CompatSink`]. pub fn new(inner: T) -> Self { - CompatSink { - inner, - _phantom: PhantomData, - } + CompatSink { inner, _phantom: PhantomData } } /// Get a reference to 0.3 Sink contained within. @@ -101,9 +86,7 @@ impl CompatSink { } } -fn poll_03_to_01(x: task03::Poll>) - -> Result, E> -{ +fn poll_03_to_01(x: task03::Poll>) -> Result, E> { match x? { task03::Poll::Ready(t) => Ok(Async01::Ready(t)), task03::Poll::Pending => Ok(Async01::NotReady), @@ -146,17 +129,10 @@ where type SinkItem = Item; type SinkError = T::Error; - fn start_send( - &mut self, - item: Self::SinkItem, - ) -> StartSend01 { - with_sink_context(self, |mut inner, cx| { - match inner.as_mut().poll_ready(cx)? { - task03::Poll::Ready(()) => { - inner.start_send(item).map(|()| AsyncSink01::Ready) - } - task03::Poll::Pending => Ok(AsyncSink01::NotReady(item)), - } + fn start_send(&mut self, item: Self::SinkItem) -> StartSend01 { + with_sink_context(self, |mut inner, cx| match inner.as_mut().poll_ready(cx)? { + task03::Poll::Ready(()) => inner.start_send(item).map(|()| AsyncSink01::Ready), + task03::Poll::Pending => Ok(AsyncSink01::NotReady(item)), }) } @@ -189,9 +165,9 @@ impl Current { // Lazily create the `Arc` only when the waker is actually cloned. // FIXME: remove `transmute` when a `Waker` -> `RawWaker` conversion // function is landed in `core`. - mem::transmute::( - task03::waker(Arc::new(ptr_to_current(ptr).clone())) - ) + mem::transmute::(task03::waker(Arc::new( + ptr_to_current(ptr).clone(), + ))) } unsafe fn drop(_: *const ()) {} unsafe fn wake(ptr: *const ()) { @@ -241,9 +217,7 @@ mod io { use futures_io::{AsyncRead as AsyncRead03, AsyncWrite as AsyncWrite03}; use tokio_io::{AsyncRead as AsyncRead01, AsyncWrite as AsyncWrite01}; - fn poll_03_to_io(x: task03::Poll>) - -> Result - { + fn poll_03_to_io(x: task03::Poll>) -> Result { match x { task03::Poll::Ready(Ok(t)) => Ok(t), task03::Poll::Pending => Err(std::io::ErrorKind::WouldBlock.into()), diff --git a/futures-util/src/compat/executor.rs b/futures-util/src/compat/executor.rs index 82cb496a70..e25705be16 100644 --- a/futures-util/src/compat/executor.rs +++ b/futures-util/src/compat/executor.rs @@ -66,9 +66,7 @@ where fn spawn_obj(&self, future: FutureObj<'static, ()>) -> Result<(), SpawnError03> { let future = future.unit_error().compat(); - self.executor01 - .execute(future) - .map_err(|_| SpawnError03::shutdown()) + self.executor01.execute(future).map_err(|_| SpawnError03::shutdown()) } } diff --git a/futures-util/src/compat/mod.rs b/futures-util/src/compat/mod.rs index 18268364ec..1c279e527a 100644 --- a/futures-util/src/compat/mod.rs +++ b/futures-util/src/compat/mod.rs @@ -4,14 +4,14 @@ //! library is activated. mod executor; -pub use self::executor::{Executor01CompatExt, Executor01Future, Executor01As03}; +pub use self::executor::{Executor01As03, Executor01CompatExt, Executor01Future}; mod compat01as03; +#[cfg(feature = "io-compat")] +pub use self::compat01as03::{AsyncRead01CompatExt, AsyncWrite01CompatExt}; pub use self::compat01as03::{Compat01As03, Future01CompatExt, Stream01CompatExt}; #[cfg(feature = "sink")] pub use self::compat01as03::{Compat01As03Sink, Sink01CompatExt}; -#[cfg(feature = "io-compat")] -pub use self::compat01as03::{AsyncRead01CompatExt, AsyncWrite01CompatExt}; mod compat03as01; pub use self::compat03as01::Compat; diff --git a/futures-util/src/future/either.rs b/futures-util/src/future/either.rs index 24fbbe79d8..0455eb44dd 100644 --- a/futures-util/src/future/either.rs +++ b/futures-util/src/future/either.rs @@ -280,10 +280,7 @@ mod if_std { A: AsyncBufRead, B: AsyncBufRead, { - fn poll_fill_buf( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { unsafe { match self.get_unchecked_mut() { Either::Left(x) => Pin::new_unchecked(x).poll_fill_buf(cx), diff --git a/futures-util/src/future/future/catch_unwind.rs b/futures-util/src/future/future/catch_unwind.rs index e88cce7e9d..81c61d618e 100644 --- a/futures-util/src/future/future/catch_unwind.rs +++ b/futures-util/src/future/future/catch_unwind.rs @@ -2,8 +2,8 @@ use futures_core::future::Future; use futures_core::task::{Context, Poll}; use pin_utils::unsafe_pinned; use std::any::Any; +use std::panic::{catch_unwind, AssertUnwindSafe, UnwindSafe}; use std::pin::Pin; -use std::panic::{catch_unwind, UnwindSafe, AssertUnwindSafe}; /// Future for the [`catch_unwind`](super::FutureExt::catch_unwind) method. #[derive(Debug)] @@ -12,7 +12,10 @@ pub struct CatchUnwind { future: Fut, } -impl CatchUnwind where Fut: Future + UnwindSafe { +impl CatchUnwind +where + Fut: Future + UnwindSafe, +{ unsafe_pinned!(future: Fut); pub(super) fn new(future: Fut) -> CatchUnwind { @@ -21,7 +24,8 @@ impl CatchUnwind where Fut: Future + UnwindSafe { } impl Future for CatchUnwind - where Fut: Future + UnwindSafe, +where + Fut: Future + UnwindSafe, { type Output = Result>; diff --git a/futures-util/src/future/future/chain.rs b/futures-util/src/future/future/chain.rs index 3f248e80fe..1ad017e855 100644 --- a/futures-util/src/future/future/chain.rs +++ b/futures-util/src/future/future/chain.rs @@ -13,25 +13,27 @@ pub(crate) enum Chain { impl Unpin for Chain {} impl Chain { - pub(crate)fn is_terminated(&self) -> bool { - if let Chain::Empty = *self { true } else { false } + pub(crate) fn is_terminated(&self) -> bool { + if let Chain::Empty = *self { + true + } else { + false + } } } impl Chain - where Fut1: Future, - Fut2: Future, +where + Fut1: Future, + Fut2: Future, { pub(crate) fn new(fut1: Fut1, data: Data) -> Chain { Chain::First(fut1, Some(data)) } - pub(crate) fn poll( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - f: F, - ) -> Poll - where F: FnOnce(Fut1::Output, Data) -> Fut2, + pub(crate) fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>, f: F) -> Poll + where + F: FnOnce(Fut1::Output, Data) -> Fut2, { let mut f = Some(f); @@ -47,7 +49,7 @@ impl Chain Chain::Second(fut2) => { return unsafe { Pin::new_unchecked(fut2) }.poll(cx); } - Chain::Empty => unreachable!() + Chain::Empty => unreachable!(), }; *this = Chain::Empty; // Drop fut1 diff --git a/futures-util/src/future/future/flatten.rs b/futures-util/src/future/future/flatten.rs index 16b3a19de9..a305c8f94c 100644 --- a/futures-util/src/future/future/flatten.rs +++ b/futures-util/src/future/future/flatten.rs @@ -8,45 +8,48 @@ use pin_utils::unsafe_pinned; /// Future for the [`flatten`](super::FutureExt::flatten) method. #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Flatten - where Fut: Future, +where + Fut: Future, { state: Chain, } impl Flatten - where Fut: Future, - Fut::Output: Future, +where + Fut: Future, + Fut::Output: Future, { unsafe_pinned!(state: Chain); pub(super) fn new(future: Fut) -> Flatten { - Flatten { - state: Chain::new(future, ()), - } + Flatten { state: Chain::new(future, ()) } } } impl fmt::Debug for Flatten - where Fut: Future + fmt::Debug, - Fut::Output: fmt::Debug, +where + Fut: Future + fmt::Debug, + Fut::Output: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Flatten") - .field("state", &self.state) - .finish() + f.debug_struct("Flatten").field("state", &self.state).finish() } } impl FusedFuture for Flatten - where Fut: Future, - Fut::Output: Future, +where + Fut: Future, + Fut::Output: Future, { - fn is_terminated(&self) -> bool { self.state.is_terminated() } + fn is_terminated(&self) -> bool { + self.state.is_terminated() + } } impl Future for Flatten - where Fut: Future, - Fut::Output: Future, +where + Fut: Future, + Fut::Output: Future, { type Output = ::Output; diff --git a/futures-util/src/future/future/flatten_stream.rs b/futures-util/src/future/future/flatten_stream.rs index d1108866ca..2854101731 100644 --- a/futures-util/src/future/future/flatten_stream.rs +++ b/futures-util/src/future/future/flatten_stream.rs @@ -15,20 +15,17 @@ impl FlattenStream { unsafe_pinned!(state: State); pub(super) fn new(future: Fut) -> FlattenStream { - FlattenStream { - state: State::Future(future) - } + FlattenStream { state: State::Future(future) } } } impl fmt::Debug for FlattenStream - where Fut: Future + fmt::Debug, - Fut::Output: fmt::Debug, +where + Fut: Future + fmt::Debug, + Fut::Output: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("FlattenStream") - .field("state", &self.state) - .finish() + f.debug_struct("FlattenStream").field("state", &self.state).finish() } } @@ -55,8 +52,9 @@ impl State { } impl FusedStream for FlattenStream - where Fut: Future, - Fut::Output: Stream + FusedStream, +where + Fut: Future, + Fut::Output: Stream + FusedStream, { fn is_terminated(&self) -> bool { match &self.state { @@ -67,8 +65,9 @@ impl FusedStream for FlattenStream } impl Stream for FlattenStream - where Fut: Future, - Fut::Output: Stream, +where + Fut: Future, + Fut::Output: Stream, { type Item = ::Item; diff --git a/futures-util/src/future/future/fuse.rs b/futures-util/src/future/future/fuse.rs index b5ef913034..0848b6636c 100644 --- a/futures-util/src/future/future/fuse.rs +++ b/futures-util/src/future/future/fuse.rs @@ -1,5 +1,5 @@ use core::pin::Pin; -use futures_core::future::{Future, FusedFuture}; +use futures_core::future::{FusedFuture, Future}; use futures_core::task::{Context, Poll}; use pin_utils::unsafe_pinned; @@ -14,9 +14,7 @@ impl Fuse { unsafe_pinned!(future: Option); pub(super) fn new(f: Fut) -> Fuse { - Fuse { - future: Some(f), - } + Fuse { future: Some(f) } } /// Creates a new `Fuse`-wrapped future which is already terminated. diff --git a/futures-util/src/future/future/inspect.rs b/futures-util/src/future/future/inspect.rs index d67455aa6d..1d88f994d0 100644 --- a/futures-util/src/future/future/inspect.rs +++ b/futures-util/src/future/future/inspect.rs @@ -16,25 +16,26 @@ impl Inspect { unsafe_unpinned!(f: Option); pub(super) fn new(future: Fut, f: F) -> Inspect { - Inspect { - future, - f: Some(f), - } + Inspect { future, f: Some(f) } } } impl Unpin for Inspect {} impl FusedFuture for Inspect - where Fut: FusedFuture, - F: FnOnce(&Fut::Output), +where + Fut: FusedFuture, + F: FnOnce(&Fut::Output), { - fn is_terminated(&self) -> bool { self.future.is_terminated() } + fn is_terminated(&self) -> bool { + self.future.is_terminated() + } } impl Future for Inspect - where Fut: Future, - F: FnOnce(&Fut::Output), +where + Fut: Future, + F: FnOnce(&Fut::Output), { type Output = Fut::Output; diff --git a/futures-util/src/future/future/into_stream.rs b/futures-util/src/future/future/into_stream.rs index 616c4cbb57..808501ace7 100644 --- a/futures-util/src/future/future/into_stream.rs +++ b/futures-util/src/future/future/into_stream.rs @@ -1,7 +1,7 @@ use crate::stream::{self, Once}; use core::pin::Pin; use futures_core::future::Future; -use futures_core::stream::{Stream, FusedStream}; +use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; use pin_utils::unsafe_pinned; @@ -9,16 +9,14 @@ use pin_utils::unsafe_pinned; #[must_use = "streams do nothing unless polled"] #[derive(Debug)] pub struct IntoStream { - inner: Once + inner: Once, } impl IntoStream { unsafe_pinned!(inner: Once); pub(super) fn new(future: Fut) -> IntoStream { - IntoStream { - inner: stream::once(future) - } + IntoStream { inner: stream::once(future) } } } diff --git a/futures-util/src/future/future/map.rs b/futures-util/src/future/future/map.rs index b5fbfb1384..a4e1e0f487 100644 --- a/futures-util/src/future/future/map.rs +++ b/futures-util/src/future/future/map.rs @@ -24,26 +24,27 @@ impl Map { impl Unpin for Map {} impl FusedFuture for Map - where Fut: Future, - F: FnOnce(Fut::Output) -> T, +where + Fut: Future, + F: FnOnce(Fut::Output) -> T, { - fn is_terminated(&self) -> bool { self.f.is_none() } + fn is_terminated(&self) -> bool { + self.f.is_none() + } } impl Future for Map - where Fut: Future, - F: FnOnce(Fut::Output) -> T, +where + Fut: Future, + F: FnOnce(Fut::Output) -> T, { type Output = T; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - self.as_mut() - .future() - .poll(cx) - .map(|output| { - let f = self.f().take() - .expect("Map must not be polled after it returned `Poll::Ready`"); - f(output) - }) + self.as_mut().future().poll(cx).map(|output| { + let f = + self.f().take().expect("Map must not be polled after it returned `Poll::Ready`"); + f(output) + }) } } diff --git a/futures-util/src/future/future/never_error.rs b/futures-util/src/future/future/never_error.rs index 5a68e6f952..dec0e39155 100644 --- a/futures-util/src/future/future/never_error.rs +++ b/futures-util/src/future/future/never_error.rs @@ -22,11 +22,14 @@ impl NeverError { impl Unpin for NeverError {} impl FusedFuture for NeverError { - fn is_terminated(&self) -> bool { self.future.is_terminated() } + fn is_terminated(&self) -> bool { + self.future.is_terminated() + } } impl Future for NeverError - where Fut: Future, +where + Fut: Future, { type Output = Result; diff --git a/futures-util/src/future/future/remote_handle.rs b/futures-util/src/future/future/remote_handle.rs index 06a6b0d1e0..1f81d77ed1 100644 --- a/futures-util/src/future/future/remote_handle.rs +++ b/futures-util/src/future/future/remote_handle.rs @@ -1,6 +1,6 @@ use { crate::future::{CatchUnwind, FutureExt}, - futures_channel::oneshot::{self, Sender, Receiver}, + futures_channel::oneshot::{self, Receiver, Sender}, futures_core::{ future::Future, task::{Context, Poll}, @@ -12,8 +12,8 @@ use { panic::{self, AssertUnwindSafe}, pin::Pin, sync::{ - Arc, atomic::{AtomicBool, Ordering}, + Arc, }, thread, }, @@ -79,9 +79,7 @@ pub struct Remote { impl fmt::Debug for Remote { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_tuple("Remote") - .field(&self.future) - .finish() + f.debug_tuple("Remote").field(&self.future).finish() } } @@ -99,7 +97,7 @@ impl Future for Remote { if let Poll::Ready(_) = self.as_mut().tx().as_mut().unwrap().poll_canceled(cx) { if !self.keep_running.load(Ordering::SeqCst) { // Cancelled, bail out - return Poll::Ready(()) + return Poll::Ready(()); } } diff --git a/futures-util/src/future/future/shared.rs b/futures-util/src/future/future/shared.rs index 65fad2d34f..47bc6f83b7 100644 --- a/futures-util/src/future/future/shared.rs +++ b/futures-util/src/future/future/shared.rs @@ -1,4 +1,4 @@ -use crate::task::{ArcWake, waker_ref}; +use crate::task::{waker_ref, ArcWake}; use futures_core::future::{FusedFuture, Future}; use futures_core::task::{Context, Poll, Waker}; use slab::Slab; @@ -54,13 +54,15 @@ unsafe impl Send for Inner where Fut: Future + Send, Fut::Output: Send + Sync, -{} +{ +} unsafe impl Sync for Inner where Fut: Future + Send, Fut::Output: Send + Sync, -{} +{ +} const IDLE: usize = 0; const POLLING: usize = 1; @@ -80,10 +82,7 @@ impl Shared { }), }; - Shared { - inner: Some(Arc::new(inner)), - waker_key: NULL_WAKER_KEY, - } + Shared { inner: Some(Arc::new(inner)), waker_key: NULL_WAKER_KEY } } } @@ -262,8 +261,7 @@ where }; unsafe { - *inner.future_or_output.get() = - FutureOrOutput::Output(output); + *inner.future_or_output.get() = FutureOrOutput::Output(output); } inner.notifier.state.store(COMPLETE, SeqCst); @@ -290,10 +288,7 @@ where Fut: Future, { fn clone(&self) -> Self { - Shared { - inner: self.inner.clone(), - waker_key: NULL_WAKER_KEY, - } + Shared { inner: self.inner.clone(), waker_key: NULL_WAKER_KEY } } } diff --git a/futures-util/src/future/future/then.rs b/futures-util/src/future/future/then.rs index 9f30f09864..4fe03acd8a 100644 --- a/futures-util/src/future/future/then.rs +++ b/futures-util/src/future/future/then.rs @@ -12,31 +12,34 @@ pub struct Then { } impl Then - where Fut1: Future, - Fut2: Future, +where + Fut1: Future, + Fut2: Future, { unsafe_pinned!(chain: Chain); /// Creates a new `Then`. pub(super) fn new(future: Fut1, f: F) -> Then { - Then { - chain: Chain::new(future, f), - } + Then { chain: Chain::new(future, f) } } } impl FusedFuture for Then - where Fut1: Future, - Fut2: Future, - F: FnOnce(Fut1::Output) -> Fut2, +where + Fut1: Future, + Fut2: Future, + F: FnOnce(Fut1::Output) -> Fut2, { - fn is_terminated(&self) -> bool { self.chain.is_terminated() } + fn is_terminated(&self) -> bool { + self.chain.is_terminated() + } } impl Future for Then - where Fut1: Future, - Fut2: Future, - F: FnOnce(Fut1::Output) -> Fut2, +where + Fut1: Future, + Fut2: Future, + F: FnOnce(Fut1::Output) -> Fut2, { type Output = Fut2::Output; diff --git a/futures-util/src/future/future/unit_error.rs b/futures-util/src/future/future/unit_error.rs index 679e988b16..2e2aec84a0 100644 --- a/futures-util/src/future/future/unit_error.rs +++ b/futures-util/src/future/future/unit_error.rs @@ -21,11 +21,14 @@ impl UnitError { impl Unpin for UnitError {} impl FusedFuture for UnitError { - fn is_terminated(&self) -> bool { self.future.is_terminated() } + fn is_terminated(&self) -> bool { + self.future.is_terminated() + } } impl Future for UnitError - where Fut: Future, +where + Fut: Future, { type Output = Result; diff --git a/futures-util/src/future/join.rs b/futures-util/src/future/join.rs index 5af5b408e9..3d7bba9778 100644 --- a/futures-util/src/future/join.rs +++ b/futures-util/src/future/join.rs @@ -1,12 +1,12 @@ #![allow(non_snake_case)] -use crate::future::{MaybeDone, maybe_done}; +use super::assert_future; +use crate::future::{maybe_done, MaybeDone}; use core::fmt; use core::pin::Pin; -use futures_core::future::{Future, FusedFuture}; +use futures_core::future::{FusedFuture, Future}; use futures_core::task::{Context, Poll}; use pin_utils::unsafe_pinned; -use super::assert_future; macro_rules! generate { ($( diff --git a/futures-util/src/future/join_all.rs b/futures-util/src/future/join_all.rs index 07408856a4..cf534b64e2 100644 --- a/futures-util/src/future/join_all.rs +++ b/futures-util/src/future/join_all.rs @@ -1,14 +1,14 @@ //! Definition of the `JoinAll` combinator, waiting for all of a list of futures //! to finish. +use alloc::boxed::Box; +use alloc::vec::Vec; use core::fmt; use core::future::Future; use core::iter::FromIterator; use core::mem; use core::pin::Pin; use core::task::{Context, Poll}; -use alloc::boxed::Box; -use alloc::vec::Vec; #[derive(Debug)] enum ElemState @@ -41,19 +41,13 @@ where } } -impl Unpin for ElemState -where - F: Future + Unpin, -{ -} +impl Unpin for ElemState where F: Future + Unpin {} fn iter_pin_mut(slice: Pin<&mut [T]>) -> impl Iterator> { // Safety: `std` _could_ make this unsound if it were to decide Pin's // invariants aren't required to transmit through slices. Otherwise this has // the same safety as a normal field pin projection. - unsafe { slice.get_unchecked_mut() } - .iter_mut() - .map(|t| unsafe { Pin::new_unchecked(t) }) + unsafe { slice.get_unchecked_mut() }.iter_mut().map(|t| unsafe { Pin::new_unchecked(t) }) } /// Future for the [`join_all`] function. @@ -71,9 +65,7 @@ where F::Output: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("JoinAll") - .field("elems", &self.elems) - .finish() + f.debug_struct("JoinAll").field("elems", &self.elems).finish() } } @@ -142,9 +134,7 @@ where if all_done { let mut elems = mem::replace(&mut self.elems, Box::pin([])); - let result = iter_pin_mut(elems.as_mut()) - .map(|e| e.take_done().unwrap()) - .collect(); + let result = iter_pin_mut(elems.as_mut()).map(|e| e.take_done().unwrap()).collect(); Poll::Ready(result) } else { Poll::Pending diff --git a/futures-util/src/future/lazy.rs b/futures-util/src/future/lazy.rs index 5e72218d1f..a11d2339ff 100644 --- a/futures-util/src/future/lazy.rs +++ b/futures-util/src/future/lazy.rs @@ -6,7 +6,7 @@ use futures_core::task::{Context, Poll}; #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Lazy { - f: Option + f: Option, } // safe because we never generate `Pin<&mut F>` @@ -32,19 +32,24 @@ impl Unpin for Lazy {} /// # }); /// ``` pub fn lazy(f: F) -> Lazy - where F: FnOnce(&mut Context<'_>) -> R, +where + F: FnOnce(&mut Context<'_>) -> R, { Lazy { f: Some(f) } } impl FusedFuture for Lazy - where F: FnOnce(&mut Context<'_>) -> R, +where + F: FnOnce(&mut Context<'_>) -> R, { - fn is_terminated(&self) -> bool { self.f.is_none() } + fn is_terminated(&self) -> bool { + self.f.is_none() + } } impl Future for Lazy - where F: FnOnce(&mut Context<'_>) -> R, +where + F: FnOnce(&mut Context<'_>) -> R, { type Output = R; diff --git a/futures-util/src/future/maybe_done.rs b/futures-util/src/future/maybe_done.rs index f16f889781..4ffd451a8b 100644 --- a/futures-util/src/future/maybe_done.rs +++ b/futures-util/src/future/maybe_done.rs @@ -66,7 +66,7 @@ impl MaybeDone { unsafe { let this = self.get_unchecked_mut(); match this { - MaybeDone::Done(_) => {}, + MaybeDone::Done(_) => {} MaybeDone::Future(_) | MaybeDone::Gone => return None, }; if let MaybeDone::Done(output) = mem::replace(this, MaybeDone::Gone) { diff --git a/futures-util/src/future/option.rs b/futures-util/src/future/option.rs index 21413525d0..45a6f223b3 100644 --- a/futures-util/src/future/option.rs +++ b/futures-util/src/future/option.rs @@ -1,7 +1,7 @@ //! Definition of the `Option` (optional step) combinator use core::pin::Pin; -use futures_core::future::{Future, FusedFuture}; +use futures_core::future::{FusedFuture, Future}; use futures_core::task::{Context, Poll}; use pin_utils::unsafe_pinned; @@ -35,10 +35,7 @@ impl OptionFuture { impl Future for OptionFuture { type Output = Option; - fn poll( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { match self.option().as_pin_mut() { Some(x) => x.poll(cx).map(Some), None => Poll::Ready(None), diff --git a/futures-util/src/future/pending.rs b/futures-util/src/future/pending.rs index 5a7bbb8d59..813db073f2 100644 --- a/futures-util/src/future/pending.rs +++ b/futures-util/src/future/pending.rs @@ -33,9 +33,7 @@ impl FusedFuture for Pending { /// # }); /// ``` pub fn pending() -> Pending { - Pending { - _data: marker::PhantomData, - } + Pending { _data: marker::PhantomData } } impl Future for Pending { @@ -46,8 +44,7 @@ impl Future for Pending { } } -impl Unpin for Pending { -} +impl Unpin for Pending {} impl Clone for Pending { fn clone(&self) -> Self { diff --git a/futures-util/src/future/poll_fn.rs b/futures-util/src/future/poll_fn.rs index b7b10be85d..c223f9ac2c 100644 --- a/futures-util/src/future/poll_fn.rs +++ b/futures-util/src/future/poll_fn.rs @@ -34,7 +34,7 @@ impl Unpin for PollFn {} /// ``` pub fn poll_fn(f: F) -> PollFn where - F: FnMut(&mut Context<'_>) -> Poll + F: FnMut(&mut Context<'_>) -> Poll, { PollFn { f } } @@ -46,7 +46,8 @@ impl fmt::Debug for PollFn { } impl Future for PollFn - where F: FnMut(&mut Context<'_>) -> Poll, +where + F: FnMut(&mut Context<'_>) -> Poll, { type Output = T; diff --git a/futures-util/src/future/select.rs b/futures-util/src/future/select.rs index 91b467dca6..f7482689b0 100644 --- a/futures-util/src/future/select.rs +++ b/futures-util/src/future/select.rs @@ -1,7 +1,7 @@ +use crate::future::{Either, FutureExt}; use core::pin::Pin; -use futures_core::future::{Future, FusedFuture}; +use futures_core::future::{FusedFuture, Future}; use futures_core::task::{Context, Poll}; -use crate::future::{Either, FutureExt}; /// Future for the [`select()`] function. #[must_use = "futures do nothing unless you `.await` or poll them"] @@ -45,7 +45,9 @@ impl Unpin for Select {} /// } /// ``` pub fn select(future1: A, future2: B) -> Select - where A: Future + Unpin, B: Future + Unpin +where + A: Future + Unpin, + B: Future + Unpin, { Select { inner: Some((future1, future2)) } } @@ -67,7 +69,7 @@ where self.inner = Some((a, b)); Poll::Pending } - } + }, } } } diff --git a/futures-util/src/future/select_all.rs b/futures-util/src/future/select_all.rs index 9f7fb245bf..7fdf37ad73 100644 --- a/futures-util/src/future/select_all.rs +++ b/futures-util/src/future/select_all.rs @@ -1,8 +1,8 @@ use crate::future::FutureExt; +use alloc::vec::Vec; use core::iter::FromIterator; use core::mem; use core::pin::Pin; -use alloc::vec::Vec; use futures_core::future::Future; use futures_core::task::{Context, Poll}; @@ -31,12 +31,11 @@ impl Unpin for SelectAll {} /// /// This function will panic if the iterator specified contains no items. pub fn select_all(iter: I) -> SelectAll - where I: IntoIterator, - I::Item: Future + Unpin, +where + I: IntoIterator, + I::Item: Future + Unpin, { - let ret = SelectAll { - inner: iter.into_iter().collect() - }; + let ret = SelectAll { inner: iter.into_iter().collect() }; assert!(!ret.inner.is_empty()); ret } @@ -45,11 +44,9 @@ impl Future for SelectAll { type Output = (Fut::Output, usize, Vec); fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - let item = self.inner.iter_mut().enumerate().find_map(|(i, f)| { - match f.poll_unpin(cx) { - Poll::Pending => None, - Poll::Ready(e) => Some((i, e)), - } + let item = self.inner.iter_mut().enumerate().find_map(|(i, f)| match f.poll_unpin(cx) { + Poll::Pending => None, + Poll::Ready(e) => Some((i, e)), }); match item { Some((idx, res)) => { diff --git a/futures-util/src/future/select_ok.rs b/futures-util/src/future/select_ok.rs index 7f4f4d65f4..9552dbdfdb 100644 --- a/futures-util/src/future/select_ok.rs +++ b/futures-util/src/future/select_ok.rs @@ -1,8 +1,8 @@ use crate::future::TryFutureExt; +use alloc::vec::Vec; use core::iter::FromIterator; use core::mem; use core::pin::Pin; -use alloc::vec::Vec; use futures_core::future::{Future, TryFuture}; use futures_core::task::{Context, Poll}; @@ -29,12 +29,11 @@ impl Unpin for SelectOk {} /// /// This function will panic if the iterator specified contains no items. pub fn select_ok(iter: I) -> SelectOk - where I: IntoIterator, - I::Item: TryFuture + Unpin, +where + I: IntoIterator, + I::Item: TryFuture + Unpin, { - let ret = SelectOk { - inner: iter.into_iter().collect() - }; + let ret = SelectOk { inner: iter.into_iter().collect() }; assert!(!ret.inner.is_empty(), "iterator provided to select_ok was empty"); ret } @@ -45,12 +44,11 @@ impl Future for SelectOk { fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { // loop until we've either exhausted all errors, a success was hit, or nothing is ready loop { - let item = self.inner.iter_mut().enumerate().find_map(|(i, f)| { - match f.try_poll_unpin(cx) { + let item = + self.inner.iter_mut().enumerate().find_map(|(i, f)| match f.try_poll_unpin(cx) { Poll::Pending => None, Poll::Ready(e) => Some((i, e)), - } - }); + }); match item { Some((idx, res)) => { // always remove Ok or Err, if it's not the last Err continue looping @@ -58,18 +56,18 @@ impl Future for SelectOk { match res { Ok(e) => { let rest = mem::replace(&mut self.inner, Vec::new()); - return Poll::Ready(Ok((e, rest))) + return Poll::Ready(Ok((e, rest))); } Err(e) => { if self.inner.is_empty() { - return Poll::Ready(Err(e)) + return Poll::Ready(Err(e)); } } } } None => { // based on the filter above, nothing is ready, return - return Poll::Pending + return Poll::Pending; } } } diff --git a/futures-util/src/future/try_future/and_then.rs b/futures-util/src/future/try_future/and_then.rs index 37333e0503..636ed53ae2 100644 --- a/futures-util/src/future/try_future/and_then.rs +++ b/futures-util/src/future/try_future/and_then.rs @@ -12,23 +12,23 @@ pub struct AndThen { } impl AndThen - where Fut1: TryFuture, - Fut2: TryFuture, +where + Fut1: TryFuture, + Fut2: TryFuture, { unsafe_pinned!(try_chain: TryChain); /// Creates a new `Then`. pub(super) fn new(future: Fut1, f: F) -> AndThen { - AndThen { - try_chain: TryChain::new(future, f), - } + AndThen { try_chain: TryChain::new(future, f) } } } impl FusedFuture for AndThen - where Fut1: TryFuture, - Fut2: TryFuture, - F: FnOnce(Fut1::Ok) -> Fut2, +where + Fut1: TryFuture, + Fut2: TryFuture, + F: FnOnce(Fut1::Ok) -> Fut2, { fn is_terminated(&self) -> bool { self.try_chain.is_terminated() @@ -36,18 +36,17 @@ impl FusedFuture for AndThen } impl Future for AndThen - where Fut1: TryFuture, - Fut2: TryFuture, - F: FnOnce(Fut1::Ok) -> Fut2, +where + Fut1: TryFuture, + Fut2: TryFuture, + F: FnOnce(Fut1::Ok) -> Fut2, { type Output = Result; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - self.try_chain().poll(cx, |result, async_op| { - match result { - Ok(ok) => TryChainAction::Future(async_op(ok)), - Err(err) => TryChainAction::Output(Err(err)), - } + self.try_chain().poll(cx, |result, async_op| match result { + Ok(ok) => TryChainAction::Future(async_op(ok)), + Err(err) => TryChainAction::Output(Err(err)), }) } } diff --git a/futures-util/src/future/try_future/err_into.rs b/futures-util/src/future/try_future/err_into.rs index 731fcae39e..01f89ef619 100644 --- a/futures-util/src/future/try_future/err_into.rs +++ b/futures-util/src/future/try_future/err_into.rs @@ -18,31 +18,28 @@ impl ErrInto { unsafe_pinned!(future: Fut); pub(super) fn new(future: Fut) -> ErrInto { - ErrInto { - future, - _marker: PhantomData, - } + ErrInto { future, _marker: PhantomData } } } impl FusedFuture for ErrInto - where Fut: TryFuture + FusedFuture, - Fut::Error: Into, +where + Fut: TryFuture + FusedFuture, + Fut::Error: Into, { - fn is_terminated(&self) -> bool { self.future.is_terminated() } + fn is_terminated(&self) -> bool { + self.future.is_terminated() + } } impl Future for ErrInto - where Fut: TryFuture, - Fut::Error: Into, +where + Fut: TryFuture, + Fut::Error: Into, { type Output = Result; - fn poll( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { - self.future().try_poll(cx) - .map(|res| res.map_err(Into::into)) + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + self.future().try_poll(cx).map(|res| res.map_err(Into::into)) } } diff --git a/futures-util/src/future/try_future/flatten_sink.rs b/futures-util/src/future/try_future/flatten_sink.rs index d6863dd2cd..9f86ec5ce9 100644 --- a/futures-util/src/future/try_future/flatten_sink.rs +++ b/futures-util/src/future/try_future/flatten_sink.rs @@ -23,9 +23,7 @@ where unsafe_pinned!(inner: FlattenStreamSink); pub(super) fn new(future: Fut) -> Self { - Self { - inner: FlattenStreamSink::new(future), - } + Self { inner: FlattenStreamSink::new(future) } } } diff --git a/futures-util/src/future/try_future/flatten_stream_sink.rs b/futures-util/src/future/try_future/flatten_stream_sink.rs index 5a56bf708d..de16871a62 100644 --- a/futures-util/src/future/try_future/flatten_stream_sink.rs +++ b/futures-util/src/future/try_future/flatten_stream_sink.rs @@ -28,9 +28,7 @@ where Fut::Ok: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("FlattenStreamSink") - .field("state", &self.state) - .finish() + f.debug_struct("FlattenStreamSink").field("state", &self.state).finish() } } @@ -41,9 +39,7 @@ where unsafe_pinned!(state: State); pub(crate) fn new(future: Fut) -> Self { - Self { - state: State::Future(future), - } + Self { state: State::Future(future) } } } @@ -136,10 +132,7 @@ where { type Error = Fut::Error; - fn poll_ready( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { ready!(self.as_mut().state().poll_future(cx)?); match self.as_mut().state().get_pin_mut() { State::StreamOrSink(s) => s.poll_ready(cx), @@ -165,10 +158,7 @@ where } } - fn poll_close( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let res = match self.as_mut().state().get_pin_mut() { State::StreamOrSink(s) => s.poll_close(cx), State::Future(_) | State::Done => Poll::Ready(Ok(())), diff --git a/futures-util/src/future/try_future/into_future.rs b/futures-util/src/future/try_future/into_future.rs index a766d5b66d..3cb0d22cfd 100644 --- a/futures-util/src/future/try_future/into_future.rs +++ b/futures-util/src/future/try_future/into_future.rs @@ -20,17 +20,16 @@ impl IntoFuture { } impl FusedFuture for IntoFuture { - fn is_terminated(&self) -> bool { self.future.is_terminated() } + fn is_terminated(&self) -> bool { + self.future.is_terminated() + } } impl Future for IntoFuture { type Output = Result; #[inline] - fn poll( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { self.future().try_poll(cx) } } diff --git a/futures-util/src/future/try_future/map_err.rs b/futures-util/src/future/try_future/map_err.rs index 8edebad86d..a84d16f4e0 100644 --- a/futures-util/src/future/try_future/map_err.rs +++ b/futures-util/src/future/try_future/map_err.rs @@ -24,29 +24,30 @@ impl MapErr { impl Unpin for MapErr {} impl FusedFuture for MapErr - where Fut: TryFuture, - F: FnOnce(Fut::Error) -> E, +where + Fut: TryFuture, + F: FnOnce(Fut::Error) -> E, { - fn is_terminated(&self) -> bool { self.f.is_none() } + fn is_terminated(&self) -> bool { + self.f.is_none() + } } impl Future for MapErr - where Fut: TryFuture, - F: FnOnce(Fut::Error) -> E, +where + Fut: TryFuture, + F: FnOnce(Fut::Error) -> E, { type Output = Result; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { - self.as_mut() - .future() - .try_poll(cx) - .map(|result| { - let f = self.as_mut().f().take() - .expect("MapErr must not be polled after it returned `Poll::Ready`"); - result.map_err(f) - }) + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + self.as_mut().future().try_poll(cx).map(|result| { + let f = self + .as_mut() + .f() + .take() + .expect("MapErr must not be polled after it returned `Poll::Ready`"); + result.map_err(f) + }) } } diff --git a/futures-util/src/future/try_future/map_ok.rs b/futures-util/src/future/try_future/map_ok.rs index ab28f1443f..6a14728635 100644 --- a/futures-util/src/future/try_future/map_ok.rs +++ b/futures-util/src/future/try_future/map_ok.rs @@ -24,8 +24,9 @@ impl MapOk { impl Unpin for MapOk {} impl FusedFuture for MapOk - where Fut: TryFuture, - F: FnOnce(Fut::Ok) -> T, +where + Fut: TryFuture, + F: FnOnce(Fut::Ok) -> T, { fn is_terminated(&self) -> bool { self.f.is_none() @@ -33,22 +34,20 @@ impl FusedFuture for MapOk } impl Future for MapOk - where Fut: TryFuture, - F: FnOnce(Fut::Ok) -> T, +where + Fut: TryFuture, + F: FnOnce(Fut::Ok) -> T, { type Output = Result; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { - self.as_mut() - .future() - .try_poll(cx) - .map(|result| { - let op = self.as_mut().f().take() - .expect("MapOk must not be polled after it returned `Poll::Ready`"); - result.map(op) - }) + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + self.as_mut().future().try_poll(cx).map(|result| { + let op = self + .as_mut() + .f() + .take() + .expect("MapOk must not be polled after it returned `Poll::Ready`"); + result.map(op) + }) } } diff --git a/futures-util/src/future/try_future/map_ok_or_else.rs b/futures-util/src/future/try_future/map_ok_or_else.rs index 730b67922c..774933eba9 100644 --- a/futures-util/src/future/try_future/map_ok_or_else.rs +++ b/futures-util/src/future/try_future/map_ok_or_else.rs @@ -26,9 +26,10 @@ impl MapOkOrElse { impl Unpin for MapOkOrElse {} impl FusedFuture for MapOkOrElse - where Fut: TryFuture, - F: FnOnce(Fut::Ok) -> T, - E: FnOnce(Fut::Error) -> T, +where + Fut: TryFuture, + F: FnOnce(Fut::Ok) -> T, + E: FnOnce(Fut::Error) -> T, { fn is_terminated(&self) -> bool { self.f.is_none() || self.e.is_none() @@ -36,24 +37,29 @@ impl FusedFuture for MapOkOrElse } impl Future for MapOkOrElse - where Fut: TryFuture, - F: FnOnce(Fut::Ok) -> T, - E: FnOnce(Fut::Error) -> T, +where + Fut: TryFuture, + F: FnOnce(Fut::Ok) -> T, + E: FnOnce(Fut::Error) -> T, { type Output = T; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { - self.as_mut() - .future() - .try_poll(cx) - .map(|result| { - match result { - Ok(i) => (self.as_mut().f().take().expect("MapOkOrElse must not be polled after it returned `Poll::Ready`"))(i), - Err(e) => (self.as_mut().e().take().expect("MapOkOrElse must not be polled after it returned `Poll::Ready`"))(e), - } - }) + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + self.as_mut().future().try_poll(cx).map(|result| match result { + Ok(i) => (self + .as_mut() + .f() + .take() + .expect("MapOkOrElse must not be polled after it returned `Poll::Ready`"))( + i + ), + Err(e) => (self + .as_mut() + .e() + .take() + .expect("MapOkOrElse must not be polled after it returned `Poll::Ready`"))( + e + ), + }) } } diff --git a/futures-util/src/future/try_future/mod.rs b/futures-util/src/future/try_future/mod.rs index e8e059e373..2c0e022d0e 100644 --- a/futures-util/src/future/try_future/mod.rs +++ b/futures-util/src/future/try_future/mod.rs @@ -172,7 +172,7 @@ pub trait TryFutureExt: TryFuture { /// The provided closure `f` will only be called if this future is resolved /// to an [`Ok`]. If it resolves to an [`Err`], panics, or is dropped, then /// the provided closure will never be invoked. - /// + /// /// The provided closure `e` will only be called if this future is resolved /// to an [`Err`]. If it resolves to an [`Ok`], panics, or is dropped, then /// the provided closure will never be invoked. @@ -189,13 +189,13 @@ pub trait TryFutureExt: TryFuture { /// let future = async { Ok::(5) }; /// let future = future.map_ok_or_else(|x| x * 2, |x| x + 3); /// assert_eq!(future.await, 8); - /// + /// /// let future = async { Err::(5) }; /// let future = future.map_ok_or_else(|x| x * 2, |x| x + 3); /// assert_eq!(future.await, 10); /// # }); /// ``` - /// + /// fn map_ok_or_else(self, e: E, f: F) -> MapOkOrElse where F: FnOnce(Self::Ok) -> T, diff --git a/futures-util/src/future/try_future/or_else.rs b/futures-util/src/future/try_future/or_else.rs index a9c006fa9f..2f9117ddc5 100644 --- a/futures-util/src/future/try_future/or_else.rs +++ b/futures-util/src/future/try_future/or_else.rs @@ -12,23 +12,23 @@ pub struct OrElse { } impl OrElse - where Fut1: TryFuture, - Fut2: TryFuture, +where + Fut1: TryFuture, + Fut2: TryFuture, { unsafe_pinned!(try_chain: TryChain); /// Creates a new `Then`. pub(super) fn new(future: Fut1, f: F) -> OrElse { - OrElse { - try_chain: TryChain::new(future, f), - } + OrElse { try_chain: TryChain::new(future, f) } } } impl FusedFuture for OrElse - where Fut1: TryFuture, - Fut2: TryFuture, - F: FnOnce(Fut1::Error) -> Fut2, +where + Fut1: TryFuture, + Fut2: TryFuture, + F: FnOnce(Fut1::Error) -> Fut2, { fn is_terminated(&self) -> bool { self.try_chain.is_terminated() @@ -36,21 +36,17 @@ impl FusedFuture for OrElse } impl Future for OrElse - where Fut1: TryFuture, - Fut2: TryFuture, - F: FnOnce(Fut1::Error) -> Fut2, +where + Fut1: TryFuture, + Fut2: TryFuture, + F: FnOnce(Fut1::Error) -> Fut2, { type Output = Result; - fn poll( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { - self.try_chain().poll(cx, |result, async_op| { - match result { - Ok(ok) => TryChainAction::Output(Ok(ok)), - Err(err) => TryChainAction::Future(async_op(err)), - } + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + self.try_chain().poll(cx, |result, async_op| match result { + Ok(ok) => TryChainAction::Output(Ok(ok)), + Err(err) => TryChainAction::Future(async_op(err)), }) } } diff --git a/futures-util/src/future/try_future/try_chain.rs b/futures-util/src/future/try_future/try_chain.rs index 662bdf2d26..d2e9d89300 100644 --- a/futures-util/src/future/try_future/try_chain.rs +++ b/futures-util/src/future/try_future/try_chain.rs @@ -13,15 +13,17 @@ pub(crate) enum TryChain { impl Unpin for TryChain {} pub(crate) enum TryChainAction - where Fut2: TryFuture, +where + Fut2: TryFuture, { Future(Fut2), Output(Result), } impl TryChain - where Fut1: TryFuture, - Fut2: TryFuture, +where + Fut1: TryFuture, + Fut2: TryFuture, { pub(crate) fn new(fut1: Fut1, data: Data) -> TryChain { TryChain::First(fut1, Some(data)) @@ -39,7 +41,8 @@ impl TryChain cx: &mut Context<'_>, f: F, ) -> Poll> - where F: FnOnce(Result, Data) -> TryChainAction, + where + F: FnOnce(Result, Data) -> TryChainAction, { let mut f = Some(f); @@ -55,12 +58,10 @@ impl TryChain } TryChain::Second(fut2) => { // Poll the second future - return unsafe { Pin::new_unchecked(fut2) } - .try_poll(cx) - .map(|res| { - *this = TryChain::Empty; // Drop fut2. - res - }); + return unsafe { Pin::new_unchecked(fut2) }.try_poll(cx).map(|res| { + *this = TryChain::Empty; // Drop fut2. + res + }); } TryChain::Empty => { panic!("future must not be polled after it returned `Poll::Ready`"); @@ -95,13 +96,10 @@ mod tests { let mut future = TryChain::new(ready(Ok(1)), ()); assert!(!future.is_terminated()); - let res = Pin::new(&mut future).poll( - &mut cx, - |res: Result, ()| { - assert!(res.is_ok()); - TryChainAction::Future(ready(Ok(2))) - }, - ); + let res = Pin::new(&mut future).poll(&mut cx, |res: Result, ()| { + assert!(res.is_ok()); + TryChainAction::Future(ready(Ok(2))) + }); assert_eq!(res, Poll::Ready::>(Ok(2))); assert!(future.is_terminated()); } diff --git a/futures-util/src/future/try_future/try_flatten_stream.rs b/futures-util/src/future/try_future/try_flatten_stream.rs index 24624314c0..6013bfcb47 100644 --- a/futures-util/src/future/try_future/try_flatten_stream.rs +++ b/futures-util/src/future/try_future/try_flatten_stream.rs @@ -25,9 +25,7 @@ where unsafe_pinned!(inner: FlattenStreamSink); pub(super) fn new(future: Fut) -> Self { - Self { - inner: FlattenStreamSink::new(future), - } + Self { inner: FlattenStreamSink::new(future) } } } @@ -37,9 +35,7 @@ where Fut::Ok: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("TryFlattenStream") - .field("inner", &self.inner) - .finish() + f.debug_struct("TryFlattenStream").field("inner", &self.inner).finish() } } diff --git a/futures-util/src/future/try_future/unwrap_or_else.rs b/futures-util/src/future/try_future/unwrap_or_else.rs index 286cc009fb..f29f08371c 100644 --- a/futures-util/src/future/try_future/unwrap_or_else.rs +++ b/futures-util/src/future/try_future/unwrap_or_else.rs @@ -25,8 +25,9 @@ impl UnwrapOrElse { impl Unpin for UnwrapOrElse {} impl FusedFuture for UnwrapOrElse - where Fut: TryFuture, - F: FnOnce(Fut::Error) -> Fut::Ok, +where + Fut: TryFuture, + F: FnOnce(Fut::Error) -> Fut::Ok, { fn is_terminated(&self) -> bool { self.f.is_none() @@ -34,22 +35,20 @@ impl FusedFuture for UnwrapOrElse } impl Future for UnwrapOrElse - where Fut: TryFuture, - F: FnOnce(Fut::Error) -> Fut::Ok, +where + Fut: TryFuture, + F: FnOnce(Fut::Error) -> Fut::Ok, { type Output = Fut::Ok; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { - self.as_mut() - .future() - .try_poll(cx) - .map(|result| { - let op = self.as_mut().f().take() - .expect("UnwrapOrElse already returned `Poll::Ready` before"); - result.unwrap_or_else(op) - }) + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + self.as_mut().future().try_poll(cx).map(|result| { + let op = self + .as_mut() + .f() + .take() + .expect("UnwrapOrElse already returned `Poll::Ready` before"); + result.unwrap_or_else(op) + }) } } diff --git a/futures-util/src/future/try_join.rs b/futures-util/src/future/try_join.rs index da85eff91d..bdfe305ae1 100644 --- a/futures-util/src/future/try_join.rs +++ b/futures-util/src/future/try_join.rs @@ -1,6 +1,6 @@ #![allow(non_snake_case)] -use crate::future::{MaybeDone, maybe_done, TryFutureExt, IntoFuture}; +use crate::future::{maybe_done, IntoFuture, MaybeDone, TryFutureExt}; use core::fmt; use core::pin::Pin; use futures_core::future::{Future, TryFuture}; diff --git a/futures-util/src/future/try_join_all.rs b/futures-util/src/future/try_join_all.rs index 30300e4e3e..00ac9db4d9 100644 --- a/futures-util/src/future/try_join_all.rs +++ b/futures-util/src/future/try_join_all.rs @@ -1,14 +1,14 @@ //! Definition of the `TryJoinAll` combinator, waiting for all of a list of //! futures to finish with either success or error. +use alloc::boxed::Box; +use alloc::vec::Vec; use core::fmt; use core::future::Future; use core::iter::FromIterator; use core::mem; use core::pin::Pin; use core::task::{Context, Poll}; -use alloc::boxed::Box; -use alloc::vec::Vec; use super::TryFuture; @@ -49,15 +49,13 @@ fn iter_pin_mut(slice: Pin<&mut [T]>) -> impl Iterator> { // Safety: `std` _could_ make this unsound if it were to decide Pin's // invariants aren't required to transmit through slices. Otherwise this has // the same safety as a normal field pin projection. - unsafe { slice.get_unchecked_mut() } - .iter_mut() - .map(|t| unsafe { Pin::new_unchecked(t) }) + unsafe { slice.get_unchecked_mut() }.iter_mut().map(|t| unsafe { Pin::new_unchecked(t) }) } enum FinalState { Pending, AllDone, - Error(E) + Error(E), } /// Future for the [`try_join_all`] function. @@ -76,9 +74,7 @@ where F::Error: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("TryJoinAll") - .field("elems", &self.elems) - .finish() + f.debug_struct("TryJoinAll").field("elems", &self.elems).finish() } } @@ -126,9 +122,7 @@ where I::Item: TryFuture, { let elems: Box<[_]> = i.into_iter().map(ElemState::Pending).collect(); - TryJoinAll { - elems: elems.into(), - } + TryJoinAll { elems: elems.into() } } impl Future for TryJoinAll @@ -150,7 +144,7 @@ where state = FinalState::Error(e); break; } - } + }, } } } @@ -159,15 +153,14 @@ where FinalState::Pending => Poll::Pending, FinalState::AllDone => { let mut elems = mem::replace(&mut self.elems, Box::pin([])); - let results = iter_pin_mut(elems.as_mut()) - .map(|e| e.take_done().unwrap()) - .collect(); + let results = + iter_pin_mut(elems.as_mut()).map(|e| e.take_done().unwrap()).collect(); Poll::Ready(Ok(results)) - }, + } FinalState::Error(e) => { let _ = mem::replace(&mut self.elems, Box::pin([])); Poll::Ready(Err(e)) - }, + } } } } diff --git a/futures-util/src/future/try_select.rs b/futures-util/src/future/try_select.rs index 56564f5b5c..a3e8bb902f 100644 --- a/futures-util/src/future/try_select.rs +++ b/futures-util/src/future/try_select.rs @@ -1,7 +1,7 @@ +use crate::future::{Either, TryFutureExt}; use core::pin::Pin; use futures_core::future::{Future, TryFuture}; use futures_core::task::{Context, Poll}; -use crate::future::{Either, TryFutureExt}; /// Future for the [`try_select()`] function. #[must_use = "futures do nothing unless you `.await` or poll them"] @@ -48,19 +48,20 @@ impl Unpin for TrySelect {} /// } /// ``` pub fn try_select(future1: A, future2: B) -> TrySelect - where A: TryFuture + Unpin, B: TryFuture + Unpin +where + A: TryFuture + Unpin, + B: TryFuture + Unpin, { TrySelect { inner: Some((future1, future2)) } } impl Future for TrySelect - where A: TryFuture, B: TryFuture +where + A: TryFuture, + B: TryFuture, { #[allow(clippy::type_complexity)] - type Output = Result< - Either<(A::Ok, B), (B::Ok, A)>, - Either<(A::Error, B), (B::Error, A)>, - >; + type Output = Result, Either<(A::Error, B), (B::Error, A)>>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let (mut a, mut b) = self.inner.take().expect("cannot poll Select twice"); @@ -74,7 +75,7 @@ impl Future for TrySelect self.inner = Some((a, b)); Poll::Pending } - } + }, } } } diff --git a/futures-util/src/io/allow_std.rs b/futures-util/src/io/allow_std.rs index 346e9babea..4caa4fc9e6 100644 --- a/futures-util/src/io/allow_std.rs +++ b/futures-util/src/io/allow_std.rs @@ -1,9 +1,9 @@ use futures_core::task::{Context, Poll}; #[cfg(feature = "read-initializer")] use futures_io::Initializer; -use futures_io::{AsyncRead, AsyncWrite, AsyncSeek, AsyncBufRead, IoSlice, IoSliceMut, SeekFrom}; -use std::{fmt, io}; +use futures_io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, IoSlice, IoSliceMut, SeekFrom}; use std::pin::Pin; +use std::{fmt, io}; /// A simple wrapper type which allows types which implement only /// implement `std::io::Read` or `std::io::Write` @@ -35,7 +35,7 @@ macro_rules! try_with_interrupt { } } } - } + }; } impl AllowStdIo { @@ -60,7 +60,10 @@ impl AllowStdIo { } } -impl io::Write for AllowStdIo where T: io::Write { +impl io::Write for AllowStdIo +where + T: io::Write, +{ fn write(&mut self, buf: &[u8]) -> io::Result { self.0.write(buf) } @@ -78,16 +81,23 @@ impl io::Write for AllowStdIo where T: io::Write { } } -impl AsyncWrite for AllowStdIo where T: io::Write { - fn poll_write(mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &[u8]) - -> Poll> - { +impl AsyncWrite for AllowStdIo +where + T: io::Write, +{ + fn poll_write( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { Poll::Ready(Ok(try_with_interrupt!(self.0.write(buf)))) } - fn poll_write_vectored(mut self: Pin<&mut Self>, _: &mut Context<'_>, bufs: &[IoSlice<'_>]) - -> Poll> - { + fn poll_write_vectored( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + bufs: &[IoSlice<'_>], + ) -> Poll> { Poll::Ready(Ok(try_with_interrupt!(self.0.write_vectored(bufs)))) } @@ -101,7 +111,10 @@ impl AsyncWrite for AllowStdIo where T: io::Write { } } -impl io::Read for AllowStdIo where T: io::Read { +impl io::Read for AllowStdIo +where + T: io::Read, +{ fn read(&mut self, buf: &mut [u8]) -> io::Result { self.0.read(buf) } @@ -123,16 +136,23 @@ impl io::Read for AllowStdIo where T: io::Read { } } -impl AsyncRead for AllowStdIo where T: io::Read { - fn poll_read(mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &mut [u8]) - -> Poll> - { +impl AsyncRead for AllowStdIo +where + T: io::Read, +{ + fn poll_read( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + buf: &mut [u8], + ) -> Poll> { Poll::Ready(Ok(try_with_interrupt!(self.0.read(buf)))) } - fn poll_read_vectored(mut self: Pin<&mut Self>, _: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>]) - -> Poll> - { + fn poll_read_vectored( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + bufs: &mut [IoSliceMut<'_>], + ) -> Poll> { Poll::Ready(Ok(try_with_interrupt!(self.0.read_vectored(bufs)))) } @@ -142,21 +162,32 @@ impl AsyncRead for AllowStdIo where T: io::Read { } } -impl io::Seek for AllowStdIo where T: io::Seek { +impl io::Seek for AllowStdIo +where + T: io::Seek, +{ fn seek(&mut self, pos: SeekFrom) -> io::Result { self.0.seek(pos) } } -impl AsyncSeek for AllowStdIo where T: io::Seek { - fn poll_seek(mut self: Pin<&mut Self>, _: &mut Context<'_>, pos: SeekFrom) - -> Poll> - { +impl AsyncSeek for AllowStdIo +where + T: io::Seek, +{ + fn poll_seek( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + pos: SeekFrom, + ) -> Poll> { Poll::Ready(Ok(try_with_interrupt!(self.0.seek(pos)))) } } -impl io::BufRead for AllowStdIo where T: io::BufRead { +impl io::BufRead for AllowStdIo +where + T: io::BufRead, +{ fn fill_buf(&mut self) -> io::Result<&[u8]> { self.0.fill_buf() } @@ -165,10 +196,11 @@ impl io::BufRead for AllowStdIo where T: io::BufRead { } } -impl AsyncBufRead for AllowStdIo where T: io::BufRead { - fn poll_fill_buf(mut self: Pin<&mut Self>, _: &mut Context<'_>) - -> Poll> - { +impl AsyncBufRead for AllowStdIo +where + T: io::BufRead, +{ + fn poll_fill_buf(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { let this: *mut Self = &mut *self as *mut _; Poll::Ready(Ok(try_with_interrupt!(unsafe { &mut *this }.0.fill_buf()))) } diff --git a/futures-util/src/io/buf_reader.rs b/futures-util/src/io/buf_reader.rs index 96d3f2815e..14add86f54 100644 --- a/futures-util/src/io/buf_reader.rs +++ b/futures-util/src/io/buf_reader.rs @@ -1,3 +1,4 @@ +use super::DEFAULT_BUF_SIZE; use futures_core::task::{Context, Poll}; #[cfg(feature = "read-initializer")] use futures_io::Initializer; @@ -6,7 +7,6 @@ use pin_utils::{unsafe_pinned, unsafe_unpinned}; use std::io::{self, Read}; use std::pin::Pin; use std::{cmp, fmt}; -use super::DEFAULT_BUF_SIZE; /// The `BufReader` struct adds buffering to any reader. /// @@ -53,12 +53,7 @@ impl BufReader { let mut buffer = Vec::with_capacity(capacity); buffer.set_len(capacity); super::initialize(&inner, &mut buffer); - Self { - inner, - buf: buffer.into_boxed_slice(), - pos: 0, - cap: 0, - } + Self { inner, buf: buffer.into_boxed_slice(), pos: 0, cap: 0 } } } @@ -150,10 +145,7 @@ impl AsyncRead for BufReader { } impl AsyncBufRead for BufReader { - fn poll_fill_buf( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let Self { inner, buf, cap, pos } = unsafe { self.get_unchecked_mut() }; let mut inner = unsafe { Pin::new_unchecked(inner) }; diff --git a/futures-util/src/io/buf_writer.rs b/futures-util/src/io/buf_writer.rs index b0afbd81f2..2bfee95e75 100644 --- a/futures-util/src/io/buf_writer.rs +++ b/futures-util/src/io/buf_writer.rs @@ -1,3 +1,4 @@ +use super::DEFAULT_BUF_SIZE; use futures_core::task::{Context, Poll}; #[cfg(feature = "read-initializer")] use futures_io::Initializer; @@ -6,7 +7,6 @@ use pin_utils::{unsafe_pinned, unsafe_unpinned}; use std::fmt; use std::io::{self, Write}; use std::pin::Pin; -use super::DEFAULT_BUF_SIZE; /// Wraps a writer and buffers its output. /// @@ -49,11 +49,7 @@ impl BufWriter { /// Creates a new `BufWriter` with the specified buffer capacity. pub fn with_capacity(cap: usize, inner: W) -> Self { - Self { - inner, - buf: Vec::with_capacity(cap), - written: 0, - } + Self { inner, buf: Vec::with_capacity(cap), written: 0 } } fn flush_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { @@ -185,10 +181,7 @@ impl AsyncRead for BufWriter { } impl AsyncBufRead for BufWriter { - fn poll_fill_buf( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.inner().poll_fill_buf(cx) } diff --git a/futures-util/src/io/chain.rs b/futures-util/src/io/chain.rs index 64bbdec87a..3b29f9e817 100644 --- a/futures-util/src/io/chain.rs +++ b/futures-util/src/io/chain.rs @@ -32,11 +32,7 @@ where unsafe_unpinned!(done_first: bool); pub(super) fn new(first: T, second: U) -> Self { - Self { - first, - second, - done_first: false, - } + Self { first, second, done_first: false } } /// Gets references to the underlying readers in this `Chain`. @@ -137,11 +133,7 @@ where U: AsyncBufRead, { fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - let Self { - first, - second, - done_first, - } = unsafe { self.get_unchecked_mut() }; + let Self { first, second, done_first } = unsafe { self.get_unchecked_mut() }; let first = unsafe { Pin::new_unchecked(first) }; let second = unsafe { Pin::new_unchecked(second) }; diff --git a/futures-util/src/io/copy.rs b/futures-util/src/io/copy.rs index 9531aab996..5007407acd 100644 --- a/futures-util/src/io/copy.rs +++ b/futures-util/src/io/copy.rs @@ -1,10 +1,10 @@ +use super::{copy_buf, BufReader, CopyBuf}; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use futures_io::{AsyncRead, AsyncWrite}; +use pin_utils::unsafe_pinned; use std::io; use std::pin::Pin; -use super::{BufReader, copy_buf, CopyBuf}; -use pin_utils::unsafe_pinned; /// Creates a future which copies all the bytes from one object to another. /// @@ -36,9 +36,7 @@ where R: AsyncRead, W: AsyncWrite + Unpin + ?Sized, { - Copy { - inner: copy_buf(BufReader::new(reader), writer), - } + Copy { inner: copy_buf(BufReader::new(reader), writer) } } /// Future for the [`copy()`] function. diff --git a/futures-util/src/io/copy_buf.rs b/futures-util/src/io/copy_buf.rs index 98811825e0..48469f24a8 100644 --- a/futures-util/src/io/copy_buf.rs +++ b/futures-util/src/io/copy_buf.rs @@ -34,11 +34,7 @@ where R: AsyncBufRead, W: AsyncWrite + Unpin + ?Sized, { - CopyBuf { - reader, - writer, - amt: 0, - } + CopyBuf { reader, writer, amt: 0 } } /// Future for the [`copy_buf()`] function. @@ -62,8 +58,9 @@ impl CopyBuf<'_, R, W> { } impl Future for CopyBuf<'_, R, W> - where R: AsyncBufRead, - W: AsyncWrite + Unpin + ?Sized, +where + R: AsyncBufRead, + W: AsyncWrite + Unpin + ?Sized, { type Output = io::Result; @@ -78,7 +75,7 @@ impl Future for CopyBuf<'_, R, W> let i = ready!(writer.as_mut().poll_write(cx, buffer))?; if i == 0 { - return Poll::Ready(Err(io::ErrorKind::WriteZero.into())) + return Poll::Ready(Err(io::ErrorKind::WriteZero.into())); } *amt += i as u64; reader.as_mut().consume(i); diff --git a/futures-util/src/io/cursor.rs b/futures-util/src/io/cursor.rs index d1359231c5..ddd06799f9 100644 --- a/futures-util/src/io/cursor.rs +++ b/futures-util/src/io/cursor.rs @@ -43,9 +43,7 @@ impl Cursor { /// # force_inference(&buff); /// ``` pub fn new(inner: T) -> Cursor { - Cursor { - inner: io::Cursor::new(inner), - } + Cursor { inner: io::Cursor::new(inner) } } /// Consumes this cursor, returning the underlying value. @@ -199,15 +197,19 @@ where macro_rules! delegate_async_write_to_stdio { () => { - fn poll_write(mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &[u8]) - -> Poll> - { + fn poll_write( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { Poll::Ready(io::Write::write(&mut self.inner, buf)) } - fn poll_write_vectored(mut self: Pin<&mut Self>, _: &mut Context<'_>, bufs: &[IoSlice<'_>]) - -> Poll> - { + fn poll_write_vectored( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + bufs: &[IoSlice<'_>], + ) -> Poll> { Poll::Ready(io::Write::write_vectored(&mut self.inner, bufs)) } @@ -218,7 +220,7 @@ macro_rules! delegate_async_write_to_stdio { fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.poll_flush(cx) } - } + }; } impl AsyncWrite for Cursor<&mut [u8]> { diff --git a/futures-util/src/io/flush.rs b/futures-util/src/io/flush.rs index 70b867a207..b50431dff4 100644 --- a/futures-util/src/io/flush.rs +++ b/futures-util/src/io/flush.rs @@ -20,7 +20,8 @@ impl<'a, W: AsyncWrite + ?Sized + Unpin> Flush<'a, W> { } impl Future for Flush<'_, W> - where W: AsyncWrite + ?Sized + Unpin, +where + W: AsyncWrite + ?Sized + Unpin, { type Output = io::Result<()>; diff --git a/futures-util/src/io/into_sink.rs b/futures-util/src/io/into_sink.rs index bdc6b34140..f2ccd5e920 100644 --- a/futures-util/src/io/into_sink.rs +++ b/futures-util/src/io/into_sink.rs @@ -1,10 +1,10 @@ use futures_core::task::{Context, Poll}; use futures_io::AsyncWrite; use futures_sink::Sink; +use pin_utils::{unsafe_pinned, unsafe_unpinned}; use std::io; -use std::pin::Pin; use std::marker::Unpin; -use pin_utils::{unsafe_pinned, unsafe_unpinned}; +use std::pin::Pin; #[derive(Debug)] struct Block { @@ -44,8 +44,7 @@ impl> IntoSink { fn poll_flush_buffer( self: Pin<&mut Self>, cx: &mut Context<'_>, - ) -> Poll> - { + ) -> Poll> { let (mut writer, buffer) = self.project(); if let Some(buffer) = buffer { loop { @@ -60,47 +59,30 @@ impl> IntoSink { *buffer = None; Poll::Ready(Ok(())) } - } impl> Sink for IntoSink { type Error = io::Error; - fn poll_ready( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> - { + fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { ready!(self.as_mut().poll_flush_buffer(cx))?; Poll::Ready(Ok(())) } #[allow(clippy::debug_assert_with_mut_call)] - fn start_send( - mut self: Pin<&mut Self>, - item: Item, - ) -> Result<(), Self::Error> - { + fn start_send(mut self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> { debug_assert!(self.as_mut().buffer().is_none()); *self.as_mut().buffer() = Some(Block { offset: 0, bytes: item }); Ok(()) } - fn poll_flush( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> - { + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { ready!(self.as_mut().poll_flush_buffer(cx))?; ready!(self.as_mut().writer().poll_flush(cx))?; Poll::Ready(Ok(())) } - fn poll_close( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> - { + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { ready!(self.as_mut().poll_flush_buffer(cx))?; ready!(self.as_mut().writer().poll_close(cx))?; Poll::Ready(Ok(())) diff --git a/futures-util/src/io/lines.rs b/futures-util/src/io/lines.rs index 2e1261689b..a4f28e7c24 100644 --- a/futures-util/src/io/lines.rs +++ b/futures-util/src/io/lines.rs @@ -1,10 +1,10 @@ +use super::read_line::read_line_internal; use futures_core::stream::Stream; use futures_core::task::{Context, Poll}; use futures_io::AsyncBufRead; use std::io; use std::mem; use std::pin::Pin; -use super::read_line::read_line_internal; /// Stream for the [`lines`](super::AsyncBufReadExt::lines) method. #[derive(Debug)] @@ -20,12 +20,7 @@ impl Unpin for Lines {} impl Lines { pub(super) fn new(reader: R) -> Self { - Self { - reader, - buf: String::new(), - bytes: Vec::new(), - read: 0, - } + Self { reader, buf: String::new(), bytes: Vec::new(), read: 0 } } } @@ -37,7 +32,7 @@ impl Stream for Lines { let reader = unsafe { Pin::new_unchecked(reader) }; let n = ready!(read_line_internal(reader, cx, buf, bytes, read))?; if n == 0 && buf.is_empty() { - return Poll::Ready(None) + return Poll::Ready(None); } if buf.ends_with('\n') { buf.pop(); diff --git a/futures-util/src/io/mod.rs b/futures-util/src/io/mod.rs index 43f183f424..7e67dc3ca6 100644 --- a/futures-util/src/io/mod.rs +++ b/futures-util/src/io/mod.rs @@ -13,12 +13,12 @@ use crate::compat::Compat; use std::ptr; -pub use futures_io::{ - AsyncRead, AsyncWrite, AsyncSeek, AsyncBufRead, Error, ErrorKind, - IoSlice, IoSliceMut, Result, SeekFrom, -}; #[cfg(feature = "read-initializer")] pub use futures_io::Initializer; +pub use futures_io::{ + AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, Error, ErrorKind, IoSlice, IoSliceMut, Result, + SeekFrom, +}; // used by `BufReader` and `BufWriter` // https://github.com/rust-lang/rust/blob/master/src/libstd/sys_common/io.rs#L1 @@ -182,7 +182,8 @@ pub trait AsyncReadExt: AsyncRead { /// # Ok::<(), Box>(()) }).unwrap(); /// ``` fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self> - where Self: Unpin, + where + Self: Unpin, { Read::new(self, buf) } @@ -193,7 +194,8 @@ pub trait AsyncReadExt: AsyncRead { /// The returned future will resolve to the number of bytes read once the read /// operation is completed. fn read_vectored<'a>(&'a mut self, bufs: &'a mut [IoSliceMut<'a>]) -> ReadVectored<'a, Self> - where Self: Unpin, + where + Self: Unpin, { ReadVectored::new(self, bufs) } @@ -235,11 +237,9 @@ pub trait AsyncReadExt: AsyncRead { /// assert_eq!(result.unwrap_err().kind(), io::ErrorKind::UnexpectedEof); /// # }); /// ``` - fn read_exact<'a>( - &'a mut self, - buf: &'a mut [u8], - ) -> ReadExact<'a, Self> - where Self: Unpin, + fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExact<'a, Self> + where + Self: Unpin, { ReadExact::new(self, buf) } @@ -263,11 +263,9 @@ pub trait AsyncReadExt: AsyncRead { /// assert_eq!(output, vec![1, 2, 3, 4]); /// # Ok::<(), Box>(()) }).unwrap(); /// ``` - fn read_to_end<'a>( - &'a mut self, - buf: &'a mut Vec, - ) -> ReadToEnd<'a, Self> - where Self: Unpin, + fn read_to_end<'a>(&'a mut self, buf: &'a mut Vec) -> ReadToEnd<'a, Self> + where + Self: Unpin, { ReadToEnd::new(self, buf) } @@ -291,11 +289,9 @@ pub trait AsyncReadExt: AsyncRead { /// assert_eq!(buffer, String::from("1234")); /// # Ok::<(), Box>(()) }).unwrap(); /// ``` - fn read_to_string<'a>( - &'a mut self, - buf: &'a mut String, - ) -> ReadToString<'a, Self> - where Self: Unpin, + fn read_to_string<'a>(&'a mut self, buf: &'a mut String) -> ReadToString<'a, Self> + where + Self: Unpin, { ReadToString::new(self, buf) } @@ -330,7 +326,8 @@ pub trait AsyncReadExt: AsyncRead { /// # Ok::<(), Box>(()) }).unwrap(); /// ``` fn split(self) -> (ReadHalf, WriteHalf) - where Self: AsyncWrite + Sized, + where + Self: AsyncWrite + Sized, { split::split(self) } @@ -355,7 +352,8 @@ pub trait AsyncReadExt: AsyncRead { /// # Ok::<(), Box>(()) }).unwrap(); /// ``` fn take(self, limit: u64) -> Take - where Self: Sized + where + Self: Sized, { Take::new(self, limit) } @@ -368,7 +366,8 @@ pub trait AsyncReadExt: AsyncRead { /// Requires the `io-compat` feature to enable. #[cfg(feature = "io-compat")] fn compat(self) -> Compat - where Self: Sized + Unpin, + where + Self: Sized + Unpin, { Compat::new(self) } @@ -401,14 +400,16 @@ pub trait AsyncWriteExt: AsyncWrite { /// # Ok::<(), Box>(()) }).unwrap(); /// ``` fn flush(&mut self) -> Flush<'_, Self> - where Self: Unpin, + where + Self: Unpin, { Flush::new(self) } /// Creates a future which will entirely close this `AsyncWrite`. fn close(&mut self) -> Close<'_, Self> - where Self: Unpin, + where + Self: Unpin, { Close::new(self) } @@ -418,7 +419,8 @@ pub trait AsyncWriteExt: AsyncWrite { /// The returned future will resolve to the number of bytes written once the write /// operation is completed. fn write<'a>(&'a mut self, buf: &'a [u8]) -> Write<'a, Self> - where Self: Unpin, + where + Self: Unpin, { Write::new(self, buf) } @@ -429,7 +431,8 @@ pub trait AsyncWriteExt: AsyncWrite { /// The returned future will resolve to the number of bytes written once the write /// operation is completed. fn write_vectored<'a>(&'a mut self, bufs: &'a [IoSlice<'a>]) -> WriteVectored<'a, Self> - where Self: Unpin, + where + Self: Unpin, { WriteVectored::new(self, bufs) } @@ -455,7 +458,8 @@ pub trait AsyncWriteExt: AsyncWrite { /// # Ok::<(), Box>(()) }).unwrap(); /// ``` fn write_all<'a>(&'a mut self, buf: &'a [u8]) -> WriteAll<'a, Self> - where Self: Unpin, + where + Self: Unpin, { WriteAll::new(self, buf) } @@ -465,12 +469,12 @@ pub trait AsyncWriteExt: AsyncWrite { /// Requires the `io-compat` feature to enable. #[cfg(feature = "io-compat")] fn compat_write(self) -> Compat - where Self: Sized + Unpin, + where + Self: Sized + Unpin, { Compat::new(self) } - /// Allow using an [`AsyncWrite`] as a [`Sink`](futures_sink::Sink)`>`. /// /// This adapter produces a sink that will write each value passed to it @@ -499,7 +503,8 @@ pub trait AsyncWriteExt: AsyncWrite { /// ``` #[cfg(feature = "sink")] fn into_sink>(self) -> IntoSink - where Self: Sized, + where + Self: Sized, { IntoSink::new(self) } @@ -515,7 +520,8 @@ pub trait AsyncSeekExt: AsyncSeek { /// In the case of an error the buffer and the object will be discarded, with /// the error yielded. fn seek(&mut self, pos: SeekFrom) -> Seek<'_, Self> - where Self: Unpin, + where + Self: Unpin, { Seek::new(self, pos) } @@ -566,12 +572,9 @@ pub trait AsyncBufReadExt: AsyncBufRead { /// assert_eq!(buf, b""); /// # Ok::<(), Box>(()) }).unwrap(); /// ``` - fn read_until<'a>( - &'a mut self, - byte: u8, - buf: &'a mut Vec, - ) -> ReadUntil<'a, Self> - where Self: Unpin, + fn read_until<'a>(&'a mut self, byte: u8, buf: &'a mut Vec) -> ReadUntil<'a, Self> + where + Self: Unpin, { ReadUntil::new(self, byte, buf) } @@ -628,7 +631,8 @@ pub trait AsyncBufReadExt: AsyncBufRead { /// # Ok::<(), Box>(()) }).unwrap(); /// ``` fn read_line<'a>(&'a mut self, buf: &'a mut String) -> ReadLine<'a, Self> - where Self: Unpin, + where + Self: Unpin, { ReadLine::new(self, buf) } @@ -666,7 +670,8 @@ pub trait AsyncBufReadExt: AsyncBufRead { /// # Ok::<(), Box>(()) }).unwrap(); /// ``` fn lines(self) -> Lines - where Self: Sized, + where + Self: Sized, { Lines::new(self) } diff --git a/futures-util/src/io/read_exact.rs b/futures-util/src/io/read_exact.rs index a2bbd400ea..f3f10c2303 100644 --- a/futures-util/src/io/read_exact.rs +++ b/futures-util/src/io/read_exact.rs @@ -33,7 +33,7 @@ impl Future for ReadExact<'_, R> { this.buf = rest; } if n == 0 { - return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())) + return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())); } } Poll::Ready(Ok(())) diff --git a/futures-util/src/io/read_line.rs b/futures-util/src/io/read_line.rs index d830514b92..1e9da3a7ff 100644 --- a/futures-util/src/io/read_line.rs +++ b/futures-util/src/io/read_line.rs @@ -1,3 +1,4 @@ +use super::read_until::read_until_internal; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use futures_io::AsyncBufRead; @@ -5,7 +6,6 @@ use std::io; use std::mem; use std::pin::Pin; use std::str; -use super::read_until::read_until_internal; /// Future for the [`read_line`](super::AsyncBufReadExt::read_line) method. #[derive(Debug)] @@ -21,12 +21,7 @@ impl Unpin for ReadLine<'_, R> {} impl<'a, R: AsyncBufRead + ?Sized + Unpin> ReadLine<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut String) -> Self { - Self { - reader, - bytes: unsafe { mem::replace(buf.as_mut_vec(), Vec::new()) }, - buf, - read: 0, - } + Self { reader, bytes: unsafe { mem::replace(buf.as_mut_vec(), Vec::new()) }, buf, read: 0 } } } diff --git a/futures-util/src/io/read_to_end.rs b/futures-util/src/io/read_to_end.rs index 70b057829c..5f00b66d30 100644 --- a/futures-util/src/io/read_to_end.rs +++ b/futures-util/src/io/read_to_end.rs @@ -19,19 +19,20 @@ impl Unpin for ReadToEnd<'_, R> {} impl<'a, R: AsyncRead + ?Sized + Unpin> ReadToEnd<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut Vec) -> Self { let start_len = buf.len(); - Self { - reader, - buf, - start_len, - } + Self { reader, buf, start_len } } } -struct Guard<'a> { buf: &'a mut Vec, len: usize } +struct Guard<'a> { + buf: &'a mut Vec, + len: usize, +} impl Drop for Guard<'_> { fn drop(&mut self) { - unsafe { self.buf.set_len(self.len); } + unsafe { + self.buf.set_len(self.len); + } } } @@ -79,7 +80,8 @@ pub(super) fn read_to_end_internal( } impl Future for ReadToEnd<'_, A> - where A: AsyncRead + ?Sized + Unpin, +where + A: AsyncRead + ?Sized + Unpin, { type Output = io::Result; diff --git a/futures-util/src/io/read_to_string.rs b/futures-util/src/io/read_to_string.rs index 56c95ce18d..0d8103bffb 100644 --- a/futures-util/src/io/read_to_string.rs +++ b/futures-util/src/io/read_to_string.rs @@ -40,10 +40,7 @@ fn read_to_string_internal( let ret = ready!(read_to_end_internal(reader, cx, bytes, start_len)); if str::from_utf8(&bytes).is_err() { Poll::Ready(ret.and_then(|_| { - Err(io::Error::new( - io::ErrorKind::InvalidData, - "stream did not contain valid UTF-8", - )) + Err(io::Error::new(io::ErrorKind::InvalidData, "stream did not contain valid UTF-8")) })) } else { debug_assert!(buf.is_empty()); diff --git a/futures-util/src/io/split.rs b/futures-util/src/io/split.rs index d12df867fc..8c91dc230d 100644 --- a/futures-util/src/io/split.rs +++ b/futures-util/src/io/split.rs @@ -16,12 +16,9 @@ pub struct WriteHalf { handle: BiLock, } -fn lock_and_then( - lock: &BiLock, - cx: &mut Context<'_>, - f: F -) -> Poll> - where F: FnOnce(Pin<&mut T>, &mut Context<'_>) -> Poll> +fn lock_and_then(lock: &BiLock, cx: &mut Context<'_>, f: F) -> Poll> +where + F: FnOnce(Pin<&mut T>, &mut Context<'_>) -> Poll>, { let mut l = ready!(lock.poll_lock(cx)); f(l.as_pin_mut(), cx) @@ -33,29 +30,37 @@ pub(super) fn split(t: T) -> (ReadHalf, WriteHalf< } impl AsyncRead for ReadHalf { - fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) - -> Poll> - { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut [u8], + ) -> Poll> { lock_and_then(&self.handle, cx, |l, cx| l.poll_read(cx, buf)) } - fn poll_read_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>]) - -> Poll> - { + fn poll_read_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &mut [IoSliceMut<'_>], + ) -> Poll> { lock_and_then(&self.handle, cx, |l, cx| l.poll_read_vectored(cx, bufs)) } } impl AsyncWrite for WriteHalf { - fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) - -> Poll> - { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { lock_and_then(&self.handle, cx, |l, cx| l.poll_write(cx, buf)) } - fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>]) - -> Poll> - { + fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[IoSlice<'_>], + ) -> Poll> { lock_and_then(&self.handle, cx, |l, cx| l.poll_write_vectored(cx, bufs)) } diff --git a/futures-util/src/io/take.rs b/futures-util/src/io/take.rs index b1f33fa468..6abc7a709d 100644 --- a/futures-util/src/io/take.rs +++ b/futures-util/src/io/take.rs @@ -1,10 +1,10 @@ use futures_core::task::{Context, Poll}; #[cfg(feature = "read-initializer")] use futures_io::Initializer; -use futures_io::{AsyncRead, AsyncBufRead}; +use futures_io::{AsyncBufRead, AsyncRead}; use pin_utils::{unsafe_pinned, unsafe_unpinned}; -use std::{cmp, io}; use std::pin::Pin; +use std::{cmp, io}; /// Reader for the [`take`](super::AsyncReadExt::take) method. #[derive(Debug)] @@ -15,7 +15,7 @@ pub struct Take { limit_: u64, } -impl Unpin for Take { } +impl Unpin for Take {} impl Take { unsafe_pinned!(inner: R); diff --git a/futures-util/src/io/window.rs b/futures-util/src/io/window.rs index 3424197d75..77b7267c69 100644 --- a/futures-util/src/io/window.rs +++ b/futures-util/src/io/window.rs @@ -30,10 +30,7 @@ impl> Window { /// Further methods can be called on the returned `Window` to alter the /// window into the data provided. pub fn new(t: T) -> Self { - Self { - range: 0..t.as_ref().len(), - inner: t, - } + Self { range: 0..t.as_ref().len(), inner: t } } /// Gets a shared reference to the underlying buffer inside of this diff --git a/futures-util/src/io/write_all.rs b/futures-util/src/io/write_all.rs index 57f1400b0e..f9ffb49ea2 100644 --- a/futures-util/src/io/write_all.rs +++ b/futures-util/src/io/write_all.rs @@ -33,7 +33,7 @@ impl Future for WriteAll<'_, W> { this.buf = rest; } if n == 0 { - return Poll::Ready(Err(io::ErrorKind::WriteZero.into())) + return Poll::Ready(Err(io::ErrorKind::WriteZero.into())); } } diff --git a/futures-util/src/lib.rs b/futures-util/src/lib.rs index 21645b148d..56ed1845dd 100644 --- a/futures-util/src/lib.rs +++ b/futures-util/src/lib.rs @@ -3,20 +3,16 @@ #![cfg_attr(feature = "cfg-target-has-atomic", feature(cfg_target_has_atomic))] #![cfg_attr(feature = "read-initializer", feature(read_initializer))] - #![cfg_attr(not(feature = "std"), no_std)] #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms, unreachable_pub)] // It cannot be included in the published code because this lints have false positives in the minimum required version. #![cfg_attr(test, warn(single_use_lifetimes))] #![warn(clippy::all)] - // The solution for this lint is not available on 1.39 which is the current minimum supported version. // Can be removed as of minimum supported 1.40 or if https://github.com/rust-lang/rust-clippy/issues/3941 // get's implemented. #![allow(clippy::mem_replace_with_default)] - #![doc(test(attr(deny(warnings), allow(dead_code, unused_assignments, unused_variables))))] - #![doc(html_root_url = "https://docs.rs/futures-util/0.3.0")] #[cfg(all(feature = "cfg-target-has-atomic", not(feature = "unstable")))] @@ -68,10 +64,7 @@ macro_rules! delegate_sink { self.$field().poll_ready(cx) } - fn start_send( - self: Pin<&mut Self>, - item: $item, - ) -> Result<(), Self::Error> { + fn start_send(self: Pin<&mut Self>, item: $item) -> Result<(), Self::Error> { self.$field().start_send(item) } @@ -88,19 +81,22 @@ macro_rules! delegate_sink { ) -> $crate::core_reexport::task::Poll> { self.$field().poll_close(cx) } - } + }; } pub mod future; -#[doc(hidden)] pub use crate::future::{FutureExt, TryFutureExt}; +#[doc(hidden)] +pub use crate::future::{FutureExt, TryFutureExt}; pub mod stream; -#[doc(hidden)] pub use crate::stream::{StreamExt, TryStreamExt}; +#[doc(hidden)] +pub use crate::stream::{StreamExt, TryStreamExt}; #[cfg(feature = "sink")] pub mod sink; #[cfg(feature = "sink")] -#[doc(hidden)] pub use crate::sink::SinkExt; +#[doc(hidden)] +pub use crate::sink::SinkExt; pub mod task; @@ -114,7 +110,8 @@ pub mod compat; pub mod io; #[cfg(feature = "io")] #[cfg(feature = "std")] -#[doc(hidden)] pub use crate::io::{AsyncReadExt, AsyncWriteExt, AsyncSeekExt, AsyncBufReadExt}; +#[doc(hidden)] +pub use crate::io::{AsyncBufReadExt, AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; cfg_target_has_atomic! { #[cfg(feature = "alloc")] diff --git a/futures-util/src/sink/buffer.rs b/futures-util/src/sink/buffer.rs index d2a3f9098b..03240e56a8 100644 --- a/futures-util/src/sink/buffer.rs +++ b/futures-util/src/sink/buffer.rs @@ -1,9 +1,9 @@ -use futures_core::stream::{Stream, FusedStream}; +use alloc::collections::VecDeque; +use core::pin::Pin; +use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; use futures_sink::Sink; use pin_utils::{unsafe_pinned, unsafe_unpinned}; -use core::pin::Pin; -use alloc::collections::VecDeque; /// Sink for the [`buffer`](super::SinkExt::buffer) method. #[derive(Debug)] @@ -24,11 +24,7 @@ impl, Item> Buffer { unsafe_unpinned!(capacity: usize); pub(super) fn new(sink: Si, capacity: usize) -> Self { - Buffer { - sink, - buf: VecDeque::with_capacity(capacity), - capacity, - } + Buffer { sink, buf: VecDeque::with_capacity(capacity), capacity } } /// Get a shared reference to the inner sink. @@ -70,7 +66,10 @@ impl, Item> Buffer { } // Forwarding impl of Stream from the underlying sink -impl Stream for Buffer where S: Sink + Stream { +impl Stream for Buffer +where + S: Sink + Stream, +{ type Item = S::Item; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { @@ -82,7 +81,10 @@ impl Stream for Buffer where S: Sink + Stream { } } -impl FusedStream for Buffer where S: Sink + FusedStream { +impl FusedStream for Buffer +where + S: Sink + FusedStream, +{ fn is_terminated(&self) -> bool { self.sink.is_terminated() } @@ -91,10 +93,7 @@ impl FusedStream for Buffer where S: Sink + FusedStream impl, Item> Sink for Buffer { type Error = Si::Error; - fn poll_ready( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if self.capacity == 0 { return self.as_mut().sink().poll_ready(cx); } @@ -108,10 +107,7 @@ impl, Item> Sink for Buffer { } } - fn start_send( - mut self: Pin<&mut Self>, - item: Item, - ) -> Result<(), Self::Error> { + fn start_send(mut self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> { if self.capacity == 0 { self.as_mut().sink().start_send(item) } else { @@ -121,20 +117,14 @@ impl, Item> Sink for Buffer { } #[allow(clippy::debug_assert_with_mut_call)] - fn poll_flush( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { ready!(self.as_mut().try_empty_buffer(cx))?; debug_assert!(self.as_mut().buf().is_empty()); self.as_mut().sink().poll_flush(cx) } #[allow(clippy::debug_assert_with_mut_call)] - fn poll_close( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { ready!(self.as_mut().try_empty_buffer(cx))?; debug_assert!(self.as_mut().buf().is_empty()); self.as_mut().sink().poll_close(cx) diff --git a/futures-util/src/sink/close.rs b/futures-util/src/sink/close.rs index 1514b4118c..aba4fe4ef8 100644 --- a/futures-util/src/sink/close.rs +++ b/futures-util/src/sink/close.rs @@ -19,20 +19,14 @@ impl Unpin for Close<'_, Si, Item> {} /// The sink itself is returned after closeing is complete. impl<'a, Si: Sink + Unpin + ?Sized, Item> Close<'a, Si, Item> { pub(super) fn new(sink: &'a mut Si) -> Self { - Close { - sink, - _phantom: PhantomData, - } + Close { sink, _phantom: PhantomData } } } impl + Unpin + ?Sized, Item> Future for Close<'_, Si, Item> { type Output = Result<(), Si::Error>; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { Pin::new(&mut self.sink).poll_close(cx) } } diff --git a/futures-util/src/sink/drain.rs b/futures-util/src/sink/drain.rs index 46de83b7c2..f46f7f25b5 100644 --- a/futures-util/src/sink/drain.rs +++ b/futures-util/src/sink/drain.rs @@ -34,31 +34,19 @@ impl Unpin for Drain {} impl Sink for Drain { type Error = Never; - fn poll_ready( - self: Pin<&mut Self>, - _cx: &mut Context<'_>, - ) -> Poll> { + fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } - fn start_send( - self: Pin<&mut Self>, - _item: T, - ) -> Result<(), Self::Error> { + fn start_send(self: Pin<&mut Self>, _item: T) -> Result<(), Self::Error> { Ok(()) } - fn poll_flush( - self: Pin<&mut Self>, - _cx: &mut Context<'_>, - ) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } - fn poll_close( - self: Pin<&mut Self>, - _cx: &mut Context<'_>, - ) -> Poll> { + fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } } diff --git a/futures-util/src/sink/err_into.rs b/futures-util/src/sink/err_into.rs index af198feaa0..d52009eafe 100644 --- a/futures-util/src/sink/err_into.rs +++ b/futures-util/src/sink/err_into.rs @@ -1,8 +1,8 @@ use crate::sink::{SinkExt, SinkMapErr}; use core::pin::Pin; -use futures_core::stream::{Stream, FusedStream}; +use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; -use futures_sink::{Sink}; +use futures_sink::Sink; use pin_utils::unsafe_pinned; /// Sink for the [`sink_err_into`](super::SinkExt::sink_err_into) method. @@ -13,15 +13,14 @@ pub struct SinkErrInto, Item, E> { } impl SinkErrInto - where Si: Sink, - Si::Error: Into, +where + Si: Sink, + Si::Error: Into, { unsafe_pinned!(sink: SinkMapErr E>); pub(super) fn new(sink: Si) -> Self { - SinkErrInto { - sink: SinkExt::sink_map_err(sink, Into::into), - } + SinkErrInto { sink: SinkExt::sink_map_err(sink, Into::into) } } /// Get a shared reference to the inner sink. @@ -49,8 +48,9 @@ impl SinkErrInto } impl Sink for SinkErrInto - where Si: Sink, - Si::Error: Into, +where + Si: Sink, + Si::Error: Into, { type Error = E; @@ -59,15 +59,13 @@ impl Sink for SinkErrInto // Forwarding impl of Stream from the underlying sink impl Stream for SinkErrInto - where S: Sink + Stream, - S::Error: Into +where + S: Sink + Stream, + S::Error: Into, { type Item = S::Item; - fn poll_next( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.sink().poll_next(cx) } @@ -77,8 +75,9 @@ impl Stream for SinkErrInto } impl FusedStream for SinkErrInto - where S: Sink + FusedStream, - S::Error: Into +where + S: Sink + FusedStream, + S::Error: Into, { fn is_terminated(&self) -> bool { self.sink.is_terminated() diff --git a/futures-util/src/sink/fanout.rs b/futures-util/src/sink/fanout.rs index 24e4de95eb..3c914a5859 100644 --- a/futures-util/src/sink/fanout.rs +++ b/futures-util/src/sink/fanout.rs @@ -11,7 +11,7 @@ use pin_utils::unsafe_pinned; #[must_use = "sinks do nothing unless polled"] pub struct Fanout { sink1: Si1, - sink2: Si2 + sink2: Si2, } impl Fanout { @@ -51,56 +51,54 @@ impl Fanout { impl Debug for Fanout { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - f.debug_struct("Fanout") - .field("sink1", &self.sink1) - .field("sink2", &self.sink2) - .finish() + f.debug_struct("Fanout").field("sink1", &self.sink1).field("sink2", &self.sink2).finish() } } impl Sink for Fanout - where Si1: Sink, - Item: Clone, - Si2: Sink +where + Si1: Sink, + Item: Clone, + Si2: Sink, { type Error = Si1::Error; - fn poll_ready( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let sink1_ready = self.as_mut().sink1().poll_ready(cx)?.is_ready(); let sink2_ready = self.as_mut().sink2().poll_ready(cx)?.is_ready(); let ready = sink1_ready && sink2_ready; - if ready { Poll::Ready(Ok(())) } else { Poll::Pending } + if ready { + Poll::Ready(Ok(())) + } else { + Poll::Pending + } } - fn start_send( - mut self: Pin<&mut Self>, - item: Item, - ) -> Result<(), Self::Error> { + fn start_send(mut self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> { self.as_mut().sink1().start_send(item.clone())?; self.as_mut().sink2().start_send(item)?; Ok(()) } - fn poll_flush( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let sink1_ready = self.as_mut().sink1().poll_flush(cx)?.is_ready(); let sink2_ready = self.as_mut().sink2().poll_flush(cx)?.is_ready(); let ready = sink1_ready && sink2_ready; - if ready { Poll::Ready(Ok(())) } else { Poll::Pending } + if ready { + Poll::Ready(Ok(())) + } else { + Poll::Pending + } } - fn poll_close( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let sink1_ready = self.as_mut().sink1().poll_close(cx)?.is_ready(); let sink2_ready = self.as_mut().sink2().poll_close(cx)?.is_ready(); let ready = sink1_ready && sink2_ready; - if ready { Poll::Ready(Ok(())) } else { Poll::Pending } + if ready { + Poll::Ready(Ok(())) + } else { + Poll::Pending + } } } diff --git a/futures-util/src/sink/flush.rs b/futures-util/src/sink/flush.rs index 86fecc45d9..94dba54802 100644 --- a/futures-util/src/sink/flush.rs +++ b/futures-util/src/sink/flush.rs @@ -23,20 +23,14 @@ impl Unpin for Flush<'_, Si, Item> {} /// all current requests are processed. impl<'a, Si: Sink + Unpin + ?Sized, Item> Flush<'a, Si, Item> { pub(super) fn new(sink: &'a mut Si) -> Self { - Flush { - sink, - _phantom: PhantomData, - } + Flush { sink, _phantom: PhantomData } } } impl + Unpin + ?Sized, Item> Future for Flush<'_, Si, Item> { type Output = Result<(), Si::Error>; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { Pin::new(&mut self.sink).poll_flush(cx) } } diff --git a/futures-util/src/sink/map_err.rs b/futures-util/src/sink/map_err.rs index e999bea78f..e47e3db0c1 100644 --- a/futures-util/src/sink/map_err.rs +++ b/futures-util/src/sink/map_err.rs @@ -1,7 +1,7 @@ use core::pin::Pin; -use futures_core::stream::{Stream, FusedStream}; +use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; -use futures_sink::{Sink}; +use futures_sink::Sink; use pin_utils::{unsafe_pinned, unsafe_unpinned}; /// Sink for the [`sink_map_err`](super::SinkExt::sink_map_err) method. @@ -51,36 +51,25 @@ impl SinkMapErr { } impl Sink for SinkMapErr - where Si: Sink, - F: FnOnce(Si::Error) -> E, +where + Si: Sink, + F: FnOnce(Si::Error) -> E, { type Error = E; - fn poll_ready( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.as_mut().sink().poll_ready(cx).map_err(|e| self.as_mut().take_f()(e)) } - fn start_send( - mut self: Pin<&mut Self>, - item: Item, - ) -> Result<(), Self::Error> { + fn start_send(mut self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> { self.as_mut().sink().start_send(item).map_err(|e| self.as_mut().take_f()(e)) } - fn poll_flush( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.as_mut().sink().poll_flush(cx).map_err(|e| self.as_mut().take_f()(e)) } - fn poll_close( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.as_mut().sink().poll_close(cx).map_err(|e| self.as_mut().take_f()(e)) } } @@ -89,10 +78,7 @@ impl Sink for SinkMapErr impl Stream for SinkMapErr { type Item = S::Item; - fn poll_next( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.sink().poll_next(cx) } diff --git a/futures-util/src/sink/mod.rs b/futures-util/src/sink/mod.rs index bc59ce5865..768ac00a02 100644 --- a/futures-util/src/sink/mod.rs +++ b/futures-util/src/sink/mod.rs @@ -6,9 +6,9 @@ //! This module is only available when the `sink` feature of this //! library is activated, and it is activated by default. +use crate::future::Either; use futures_core::future::Future; use futures_core::stream::{Stream, TryStream}; -use crate::future::Either; #[cfg(feature = "compat")] use crate::compat::CompatSink; @@ -67,10 +67,11 @@ pub trait SinkExt: Sink { /// Note that this function consumes the given sink, returning a wrapped /// version, much like `Iterator::map`. fn with(self, f: F) -> With - where F: FnMut(U) -> Fut, - Fut: Future>, - E: From, - Self: Sized + where + F: FnMut(U) -> Fut, + Fut: Future>, + E: From, + Self: Sized, { With::new(self, f) } @@ -108,9 +109,10 @@ pub trait SinkExt: Sink { /// # }); /// ``` fn with_flat_map(self, f: F) -> WithFlatMap - where F: FnMut(U) -> St, - St: Stream>, - Self: Sized + where + F: FnMut(U) -> St, + St: Stream>, + Self: Sized, { WithFlatMap::new(self, f) } @@ -131,8 +133,9 @@ pub trait SinkExt: Sink { /// Transforms the error returned by the sink. fn sink_map_err(self, f: F) -> SinkMapErr - where F: FnOnce(Self::Error) -> E, - Self: Sized, + where + F: FnOnce(Self::Error) -> E, + Self: Sized, { SinkMapErr::new(self, f) } @@ -141,13 +144,13 @@ pub trait SinkExt: Sink { /// /// If wanting to map errors of a `Sink + Stream`, use `.sink_err_into().err_into()`. fn sink_err_into(self) -> err_into::SinkErrInto - where Self: Sized, - Self::Error: Into, + where + Self: Sized, + Self::Error: Into, { SinkErrInto::new(self) } - /// Adds a fixed-size buffer to the current sink. /// /// The resulting sink will buffer up to `capacity` items when the @@ -162,14 +165,16 @@ pub trait SinkExt: Sink { /// library is activated, and it is activated by default. #[cfg(feature = "alloc")] fn buffer(self, capacity: usize) -> Buffer - where Self: Sized, + where + Self: Sized, { Buffer::new(self, capacity) } /// Close the sink. fn close(&mut self) -> Close<'_, Self, Item> - where Self: Unpin, + where + Self: Unpin, { Close::new(self) } @@ -179,9 +184,10 @@ pub trait SinkExt: Sink { /// This adapter clones each incoming item and forwards it to both this as well as /// the other sink at the same time. fn fanout(self, other: Si) -> Fanout - where Self: Sized, - Item: Clone, - Si: Sink + where + Self: Sized, + Item: Clone, + Si: Sink, { Fanout::new(self, other) } @@ -191,7 +197,8 @@ pub trait SinkExt: Sink { /// This adapter is intended to be used when you want to stop sending to the sink /// until all current requests are processed. fn flush(&mut self) -> Flush<'_, Self, Item> - where Self: Unpin, + where + Self: Unpin, { Flush::new(self) } @@ -203,7 +210,8 @@ pub trait SinkExt: Sink { /// to batch together items to send via `send_all`, rather than flushing /// between each item.** fn send(&mut self, item: Item) -> Send<'_, Self, Item> - where Self: Unpin, + where + Self: Unpin, { Send::new(self, item) } @@ -219,12 +227,10 @@ pub trait SinkExt: Sink { /// Doing `sink.send_all(stream)` is roughly equivalent to /// `stream.forward(sink)`. The returned future will exhaust all items from /// `stream` and send them to `self`. - fn send_all<'a, St>( - &'a mut self, - stream: &'a mut St - ) -> SendAll<'a, Self, St> - where St: TryStream + Stream + Unpin + ?Sized, - Self: Unpin, + fn send_all<'a, St>(&'a mut self, stream: &'a mut St) -> SendAll<'a, Self, St> + where + St: TryStream + Stream + Unpin + ?Sized, + Self: Unpin, { SendAll::new(self, stream) } @@ -235,8 +241,9 @@ pub trait SinkExt: Sink { /// This can be used in combination with the `right_sink` method to write `if` /// statements that evaluate to different streams in different branches. fn left_sink(self) -> Either - where Si2: Sink, - Self: Sized + where + Si2: Sink, + Self: Sized, { Either::Left(self) } @@ -247,8 +254,9 @@ pub trait SinkExt: Sink { /// This can be used in combination with the `left_sink` method to write `if` /// statements that evaluate to different streams in different branches. fn right_sink(self) -> Either - where Si1: Sink, - Self: Sized + where + Si1: Sink, + Self: Sized, { Either::Right(self) } @@ -257,7 +265,8 @@ pub trait SinkExt: Sink { /// futures 0.1 `Sink`. Requires the `compat` feature to be enabled. #[cfg(feature = "compat")] fn compat(self) -> CompatSink - where Self: Sized + Unpin, + where + Self: Sized + Unpin, { CompatSink::new(self) } diff --git a/futures-util/src/sink/send.rs b/futures-util/src/sink/send.rs index dc7f0be254..3858e5b5b7 100644 --- a/futures-util/src/sink/send.rs +++ b/futures-util/src/sink/send.rs @@ -16,20 +16,14 @@ impl Unpin for Send<'_, Si, Item> {} impl<'a, Si: Sink + Unpin + ?Sized, Item> Send<'a, Si, Item> { pub(super) fn new(sink: &'a mut Si, item: Item) -> Self { - Send { - sink, - item: Some(item), - } + Send { sink, item: Some(item) } } } impl + Unpin + ?Sized, Item> Future for Send<'_, Si, Item> { type Output = Result<(), Si::Error>; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = &mut *self; if let Some(item) = this.item.take() { let mut sink = Pin::new(&mut this.sink); diff --git a/futures-util/src/sink/send_all.rs b/futures-util/src/sink/send_all.rs index 255df4daea..14e41f93b9 100644 --- a/futures-util/src/sink/send_all.rs +++ b/futures-util/src/sink/send_all.rs @@ -1,8 +1,8 @@ -use crate::stream::{StreamExt, TryStreamExt, Fuse}; +use crate::stream::{Fuse, StreamExt, TryStreamExt}; use core::fmt; use core::pin::Pin; use futures_core::future::Future; -use futures_core::stream::{TryStream, Stream}; +use futures_core::stream::{Stream, TryStream}; use futures_core::task::{Context, Poll}; use futures_sink::Sink; @@ -39,22 +39,16 @@ impl Unpin for SendAll<'_, Si, St> where Si: Unpin + ?Sized, St: TryStream + Unpin + ?Sized, -{} +{ +} impl<'a, Si, St, Ok, Error> SendAll<'a, Si, St> where Si: Sink + Unpin + ?Sized, St: TryStream + Stream + Unpin + ?Sized, { - pub(super) fn new( - sink: &'a mut Si, - stream: &'a mut St, - ) -> SendAll<'a, Si, St> { - SendAll { - sink, - stream: stream.fuse(), - buffered: None, - } + pub(super) fn new(sink: &'a mut Si, stream: &'a mut St) -> SendAll<'a, Si, St> { + SendAll { sink, stream: stream.fuse(), buffered: None } } fn try_start_send( @@ -64,9 +58,7 @@ where ) -> Poll> { debug_assert!(self.buffered.is_none()); match Pin::new(&mut self.sink).poll_ready(cx)? { - Poll::Ready(()) => { - Poll::Ready(Pin::new(&mut self.sink).start_send(item)) - } + Poll::Ready(()) => Poll::Ready(Pin::new(&mut self.sink).start_send(item)), Poll::Pending => { self.buffered = Some(item); Poll::Pending @@ -82,10 +74,7 @@ where { type Output = Result<(), Error>; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = &mut *self; // If we've got an item buffered already, we need to write it to the // sink before we can do anything else @@ -95,16 +84,14 @@ where loop { match this.stream.try_poll_next_unpin(cx)? { - Poll::Ready(Some(item)) => { - ready!(this.try_start_send(cx, item))? - } + Poll::Ready(Some(item)) => ready!(this.try_start_send(cx, item))?, Poll::Ready(None) => { ready!(Pin::new(&mut this.sink).poll_flush(cx))?; - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); } Poll::Pending => { ready!(Pin::new(&mut this.sink).poll_flush(cx))?; - return Poll::Pending + return Poll::Pending; } } } diff --git a/futures-util/src/sink/with.rs b/futures-util/src/sink/with.rs index 5acac0176e..df22814b39 100644 --- a/futures-util/src/sink/with.rs +++ b/futures-util/src/sink/with.rs @@ -20,7 +20,8 @@ impl Unpin for With where Si: Unpin, Fut: Unpin, -{} +{ +} impl fmt::Debug for With where @@ -28,48 +29,39 @@ where Fut: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("With") - .field("sink", &self.sink) - .field("state", &self.state) - .finish() + f.debug_struct("With").field("sink", &self.sink).field("state", &self.state).finish() } } impl With -where Si: Sink, - F: FnMut(U) -> Fut, - Fut: Future, +where + Si: Sink, + F: FnMut(U) -> Fut, + Fut: Future, { unsafe_pinned!(sink: Si); unsafe_unpinned!(f: F); unsafe_pinned!(state: Option); pub(super) fn new(sink: Si, f: F) -> Self - where - Fut: Future>, - E: From, + where + Fut: Future>, + E: From, { - With { - state: None, - sink, - f, - _phantom: PhantomData, - } + With { state: None, sink, f, _phantom: PhantomData } } } // Forwarding impl of Stream from the underlying sink impl Stream for With - where S: Stream + Sink, - F: FnMut(U) -> Fut, - Fut: Future +where + S: Stream + Sink, + F: FnMut(U) -> Fut, + Fut: Future, { type Item = S::Item; - fn poll_next( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.sink().poll_next(cx) } @@ -79,10 +71,11 @@ impl Stream for With } impl With - where Si: Sink, - F: FnMut(U) -> Fut, - Fut: Future>, - E: From, +where + Si: Sink, + F: FnMut(U) -> Fut, + Fut: Future>, + E: From, { /// Get a shared reference to the inner sink. pub fn get_ref(&self) -> &Si { @@ -108,10 +101,7 @@ impl With } /// Completes the processing of previous item if any. - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let item = match self.as_mut().state().as_pin_mut() { None => return Poll::Ready(Ok(())), Some(fut) => ready!(fut.poll(cx))?, @@ -123,44 +113,33 @@ impl With } impl Sink for With - where Si: Sink, - F: FnMut(U) -> Fut, - Fut: Future>, - E: From, +where + Si: Sink, + F: FnMut(U) -> Fut, + Fut: Future>, + E: From, { type Error = E; - fn poll_ready( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { ready!(self.as_mut().poll(cx))?; ready!(self.as_mut().sink().poll_ready(cx)?); Poll::Ready(Ok(())) } - fn start_send( - mut self: Pin<&mut Self>, - item: U, - ) -> Result<(), Self::Error> { + fn start_send(mut self: Pin<&mut Self>, item: U) -> Result<(), Self::Error> { let future = (self.as_mut().f())(item); self.as_mut().state().set(Some(future)); Ok(()) } - fn poll_flush( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { ready!(self.as_mut().poll(cx))?; ready!(self.as_mut().sink().poll_flush(cx))?; Poll::Ready(Ok(())) } - fn poll_close( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { ready!(self.as_mut().poll(cx))?; ready!(self.as_mut().sink().poll_close(cx))?; Poll::Ready(Ok(())) diff --git a/futures-util/src/sink/with_flat_map.rs b/futures-util/src/sink/with_flat_map.rs index 05ab77e7b1..4f6a0a07d7 100644 --- a/futures-util/src/sink/with_flat_map.rs +++ b/futures-util/src/sink/with_flat_map.rs @@ -1,7 +1,7 @@ use core::fmt; use core::marker::PhantomData; use core::pin::Pin; -use futures_core::stream::{Stream, FusedStream}; +use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; use futures_sink::Sink; use pin_utils::{unsafe_pinned, unsafe_unpinned}; @@ -20,7 +20,8 @@ impl Unpin for WithFlatMap where Si: Unpin, St: Unpin, -{} +{ +} impl fmt::Debug for WithFlatMap where @@ -48,13 +49,7 @@ where unsafe_pinned!(stream: Option); pub(super) fn new(sink: Si, f: F) -> Self { - WithFlatMap { - sink, - f, - stream: None, - buffer: None, - _marker: PhantomData, - } + WithFlatMap { sink, f, stream: None, buffer: None, _marker: PhantomData } } /// Get a shared reference to the inner sink. @@ -80,12 +75,8 @@ where self.sink } - fn try_empty_stream( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { - let WithFlatMap { sink, stream, buffer, .. } = - unsafe { self.get_unchecked_mut() }; + fn try_empty_stream(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let WithFlatMap { sink, stream, buffer, .. } = unsafe { self.get_unchecked_mut() }; let mut sink = unsafe { Pin::new_unchecked(sink) }; let mut stream = unsafe { Pin::new_unchecked(stream) }; @@ -119,10 +110,7 @@ where { type Item = S::Item; - fn poll_next( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.sink().poll_next(cx) } @@ -150,35 +138,23 @@ where { type Error = Si::Error; - fn poll_ready( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.try_empty_stream(cx) } - fn start_send( - mut self: Pin<&mut Self>, - item: U, - ) -> Result<(), Self::Error> { + fn start_send(mut self: Pin<&mut Self>, item: U) -> Result<(), Self::Error> { assert!(self.stream.is_none()); let stream = (self.as_mut().f())(item); self.stream().set(Some(stream)); Ok(()) } - fn poll_flush( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { ready!(self.as_mut().try_empty_stream(cx)?); self.as_mut().sink().poll_flush(cx) } - fn poll_close( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { ready!(self.as_mut().try_empty_stream(cx)?); self.as_mut().sink().poll_close(cx) } diff --git a/futures-util/src/stream/empty.rs b/futures-util/src/stream/empty.rs index 903af6851d..e4afdf3833 100644 --- a/futures-util/src/stream/empty.rs +++ b/futures-util/src/stream/empty.rs @@ -7,16 +7,14 @@ use futures_core::task::{Context, Poll}; #[derive(Debug)] #[must_use = "streams do nothing unless polled"] pub struct Empty { - _phantom: PhantomData + _phantom: PhantomData, } /// Creates a stream which contains no elements. /// /// The returned stream will always return `Ready(None)` when polled. pub fn empty() -> Empty { - Empty { - _phantom: PhantomData - } + Empty { _phantom: PhantomData } } impl Unpin for Empty {} diff --git a/futures-util/src/stream/iter.rs b/futures-util/src/stream/iter.rs index e9df81cef0..95fdd05cd3 100644 --- a/futures-util/src/stream/iter.rs +++ b/futures-util/src/stream/iter.rs @@ -26,15 +26,15 @@ impl Unpin for Iter {} /// # }); /// ``` pub fn iter(i: I) -> Iter - where I: IntoIterator, +where + I: IntoIterator, { - Iter { - iter: i.into_iter(), - } + Iter { iter: i.into_iter() } } impl Stream for Iter - where I: Iterator, +where + I: Iterator, { type Item = I::Item; diff --git a/futures-util/src/stream/mod.rs b/futures-util/src/stream/mod.rs index ba3575bf02..e7d44b4cc4 100644 --- a/futures-util/src/stream/mod.rs +++ b/futures-util/src/stream/mod.rs @@ -14,8 +14,8 @@ pub use futures_core::stream::{FusedStream, Stream, TryStream}; mod stream; pub use self::stream::{ Chain, Collect, Concat, Enumerate, Filter, FilterMap, Flatten, Fold, ForEach, Fuse, Inspect, - Map, Next, Peek, Peekable, Scan, SelectNextSome, Skip, SkipWhile, StreamExt, StreamFuture, Take, - TakeWhile, Then, Zip, + Map, Next, Peek, Peekable, Scan, SelectNextSome, Skip, SkipWhile, StreamExt, StreamFuture, + Take, TakeWhile, Then, Zip, }; #[cfg(feature = "std")] diff --git a/futures-util/src/stream/once.rs b/futures-util/src/stream/once.rs index 4f68b0cedd..7177ae6636 100644 --- a/futures-util/src/stream/once.rs +++ b/futures-util/src/stream/once.rs @@ -1,6 +1,6 @@ use core::pin::Pin; use futures_core::future::Future; -use futures_core::stream::{Stream, FusedStream}; +use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; use pin_utils::unsafe_pinned; @@ -25,7 +25,7 @@ pub fn once(future: Fut) -> Once { #[derive(Debug)] #[must_use = "streams do nothing unless polled"] pub struct Once { - future: Option + future: Option, } impl Unpin for Once {} diff --git a/futures-util/src/stream/repeat.rs b/futures-util/src/stream/repeat.rs index 21749eb71d..92208ed86c 100644 --- a/futures-util/src/stream/repeat.rs +++ b/futures-util/src/stream/repeat.rs @@ -1,5 +1,5 @@ use core::pin::Pin; -use futures_core::stream::{Stream, FusedStream}; +use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; /// Stream for the [`repeat`] function. @@ -24,7 +24,8 @@ pub struct Repeat { /// # }); /// ``` pub fn repeat(item: T) -> Repeat - where T: Clone +where + T: Clone, { Repeat { item } } @@ -32,7 +33,8 @@ pub fn repeat(item: T) -> Repeat impl Unpin for Repeat {} impl Stream for Repeat - where T: Clone +where + T: Clone, { type Item = T; @@ -46,7 +48,8 @@ impl Stream for Repeat } impl FusedStream for Repeat - where T: Clone, +where + T: Clone, { fn is_terminated(&self) -> bool { false diff --git a/futures-util/src/stream/select.rs b/futures-util/src/stream/select.rs index b5fb8133b2..8e0eda358c 100644 --- a/futures-util/src/stream/select.rs +++ b/futures-util/src/stream/select.rs @@ -1,4 +1,4 @@ -use crate::stream::{StreamExt, Fuse}; +use crate::stream::{Fuse, StreamExt}; use core::pin::Pin; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; @@ -25,14 +25,11 @@ impl Unpin for Select {} /// Note that this function consumes both streams and returns a wrapped /// version of them. pub fn select(stream1: St1, stream2: St2) -> Select - where St1: Stream, - St2: Stream +where + St1: Stream, + St2: Stream, { - Select { - stream1: stream1.fuse(), - stream2: stream2.fuse(), - flag: false, - } + Select { stream1: stream1.fuse(), stream2: stream2.fuse(), flag: false } } impl Select { @@ -73,8 +70,9 @@ impl Select { } impl FusedStream for Select - where St1: Stream, - St2: Stream +where + St1: Stream, + St2: Stream, { fn is_terminated(&self) -> bool { self.stream1.is_terminated() && self.stream2.is_terminated() @@ -82,17 +80,14 @@ impl FusedStream for Select } impl Stream for Select - where St1: Stream, - St2: Stream +where + St1: Stream, + St2: Stream, { type Item = St1::Item; - fn poll_next( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { - let Select { flag, stream1, stream2 } = - unsafe { self.get_unchecked_mut() }; + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let Select { flag, stream1, stream2 } = unsafe { self.get_unchecked_mut() }; let stream1 = unsafe { Pin::new_unchecked(stream1) }; let stream2 = unsafe { Pin::new_unchecked(stream2) }; @@ -108,24 +103,24 @@ fn poll_inner( flag: &mut bool, a: Pin<&mut St1>, b: Pin<&mut St2>, - cx: &mut Context<'_> + cx: &mut Context<'_>, ) -> Poll> - where St1: Stream, St2: Stream +where + St1: Stream, + St2: Stream, { let a_done = match a.poll_next(cx) { Poll::Ready(Some(item)) => { // give the other stream a chance to go first next time *flag = !*flag; - return Poll::Ready(Some(item)) - }, + return Poll::Ready(Some(item)); + } Poll::Ready(None) => true, Poll::Pending => false, }; match b.poll_next(cx) { - Poll::Ready(Some(item)) => { - Poll::Ready(Some(item)) - } + Poll::Ready(Some(item)) => Poll::Ready(Some(item)), Poll::Ready(None) if a_done => Poll::Ready(None), Poll::Ready(None) | Poll::Pending => Poll::Pending, } diff --git a/futures-util/src/stream/stream/catch_unwind.rs b/futures-util/src/stream/stream/catch_unwind.rs index 8d2dcf7663..a7f824545d 100644 --- a/futures-util/src/stream/stream/catch_unwind.rs +++ b/futures-util/src/stream/stream/catch_unwind.rs @@ -1,9 +1,9 @@ -use futures_core::stream::{Stream, FusedStream}; +use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; use pin_utils::{unsafe_pinned, unsafe_unpinned}; use std::any::Any; +use std::panic::{catch_unwind, AssertUnwindSafe, UnwindSafe}; use std::pin::Pin; -use std::panic::{catch_unwind, UnwindSafe, AssertUnwindSafe}; /// Stream for the [`catch_unwind`](super::StreamExt::catch_unwind) method. #[derive(Debug)] @@ -25,23 +25,18 @@ impl CatchUnwind { impl Stream for CatchUnwind { type Item = Result>; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if self.caught_unwind { Poll::Ready(None) } else { - let res = catch_unwind(AssertUnwindSafe(|| { - self.as_mut().stream().poll_next(cx) - })); + let res = catch_unwind(AssertUnwindSafe(|| self.as_mut().stream().poll_next(cx))); match res { Ok(poll) => poll.map(|opt| opt.map(Ok)), Err(e) => { *self.as_mut().caught_unwind() = true; Poll::Ready(Some(Err(e))) - }, + } } } } diff --git a/futures-util/src/stream/stream/chain.rs b/futures-util/src/stream/stream/chain.rs index b2ada69c11..d45a2e0d93 100644 --- a/futures-util/src/stream/stream/chain.rs +++ b/futures-util/src/stream/stream/chain.rs @@ -13,23 +13,22 @@ pub struct Chain { // All interactions with `Pin<&mut Chain<..>>` happen through these methods impl Chain -where St1: Stream, - St2: Stream, +where + St1: Stream, + St2: Stream, { unsafe_pinned!(first: Option); unsafe_pinned!(second: St2); pub(super) fn new(stream1: St1, stream2: St2) -> Chain { - Chain { - first: Some(stream1), - second: stream2, - } + Chain { first: Some(stream1), second: stream2 } } } impl FusedStream for Chain -where St1: Stream, - St2: FusedStream, +where + St1: Stream, + St2: FusedStream, { fn is_terminated(&self) -> bool { self.first.is_none() && self.second.is_terminated() @@ -37,18 +36,16 @@ where St1: Stream, } impl Stream for Chain -where St1: Stream, - St2: Stream, +where + St1: Stream, + St2: Stream, { type Item = St1::Item; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if let Some(first) = self.as_mut().first().as_pin_mut() { if let Some(item) = ready!(first.poll_next(cx)) { - return Poll::Ready(Some(item)) + return Poll::Ready(Some(item)); } } self.as_mut().first().set(None); @@ -64,7 +61,7 @@ where St1: Stream, let upper = match (first_upper, second_upper) { (Some(x), Some(y)) => x.checked_add(y), - _ => None + _ => None, }; (lower, upper) diff --git a/futures-util/src/stream/stream/chunks.rs b/futures-util/src/stream/stream/chunks.rs index b42d1d178d..ff019ef707 100644 --- a/futures-util/src/stream/stream/chunks.rs +++ b/futures-util/src/stream/stream/chunks.rs @@ -1,12 +1,12 @@ use crate::stream::Fuse; -use futures_core::stream::{Stream, FusedStream}; +use alloc::vec::Vec; +use core::mem; +use core::pin::Pin; +use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_utils::{unsafe_pinned, unsafe_unpinned}; -use core::mem; -use core::pin::Pin; -use alloc::vec::Vec; /// Stream for the [`chunks`](super::StreamExt::chunks) method. #[derive(Debug)] @@ -19,8 +19,11 @@ pub struct Chunks { impl Unpin for Chunks {} -impl Chunks where St: Stream { - unsafe_unpinned!(items: Vec); +impl Chunks +where + St: Stream, +{ + unsafe_unpinned!(items: Vec); unsafe_pinned!(stream: Fuse); pub(super) fn new(stream: St, capacity: usize) -> Chunks { @@ -74,10 +77,7 @@ impl Chunks where St: Stream { impl Stream for Chunks { type Item = Vec; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { loop { match ready!(self.as_mut().stream().poll_next(cx)) { // Push the item into the buffer and check whether it is full. @@ -86,7 +86,7 @@ impl Stream for Chunks { Some(item) => { self.as_mut().items().push(item); if self.items.len() >= self.cap { - return Poll::Ready(Some(self.as_mut().take())) + return Poll::Ready(Some(self.as_mut().take())); } } diff --git a/futures-util/src/stream/stream/collect.rs b/futures-util/src/stream/stream/collect.rs index 127a3f7d25..a00b0ea09b 100644 --- a/futures-util/src/stream/stream/collect.rs +++ b/futures-util/src/stream/stream/collect.rs @@ -24,16 +24,14 @@ impl Collect { } pub(super) fn new(stream: St) -> Collect { - Collect { - stream, - collection: Default::default(), - } + Collect { stream, collection: Default::default() } } } impl FusedFuture for Collect -where St: FusedStream, - C: Default + Extend +where + St: FusedStream, + C: Default + Extend, { fn is_terminated(&self) -> bool { self.stream.is_terminated() @@ -41,8 +39,9 @@ where St: FusedStream, } impl Future for Collect -where St: Stream, - C: Default + Extend +where + St: Stream, + C: Default + Extend, { type Output = C; diff --git a/futures-util/src/stream/stream/concat.rs b/futures-util/src/stream/stream/concat.rs index 704efc79fd..5a081e68eb 100644 --- a/futures-util/src/stream/stream/concat.rs +++ b/futures-util/src/stream/stream/concat.rs @@ -1,6 +1,6 @@ use core::pin::Pin; -use futures_core::future::{Future, FusedFuture}; -use futures_core::stream::{Stream, FusedStream}; +use futures_core::future::{FusedFuture, Future}; +use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; use pin_utils::{unsafe_pinned, unsafe_unpinned}; @@ -15,36 +15,29 @@ pub struct Concat { impl Unpin for Concat {} impl Concat -where St: Stream, - St::Item: Extend<::Item> + - IntoIterator + Default, +where + St: Stream, + St::Item: Extend<::Item> + IntoIterator + Default, { unsafe_pinned!(stream: St); unsafe_unpinned!(accum: Option); pub(super) fn new(stream: St) -> Concat { - Concat { - stream, - accum: None, - } + Concat { stream, accum: None } } } impl Future for Concat -where St: Stream, - St::Item: Extend<::Item> + - IntoIterator + Default, +where + St: Stream, + St::Item: Extend<::Item> + IntoIterator + Default, { type Output = St::Item; - fn poll( - mut self: Pin<&mut Self>, cx: &mut Context<'_> - ) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { loop { match ready!(self.as_mut().stream().poll_next(cx)) { - None => { - return Poll::Ready(self.as_mut().accum().take().unwrap_or_default()) - } + None => return Poll::Ready(self.as_mut().accum().take().unwrap_or_default()), Some(e) => { let accum = self.as_mut().accum(); if let Some(a) = accum { @@ -59,9 +52,9 @@ where St: Stream, } impl FusedFuture for Concat -where St: FusedStream, - St::Item: Extend<::Item> + - IntoIterator + Default, +where + St: FusedStream, + St::Item: Extend<::Item> + IntoIterator + Default, { fn is_terminated(&self) -> bool { self.accum.is_none() && self.stream.is_terminated() diff --git a/futures-util/src/stream/stream/enumerate.rs b/futures-util/src/stream/stream/enumerate.rs index 6366c8b7f3..9963a9e4fa 100644 --- a/futures-util/src/stream/stream/enumerate.rs +++ b/futures-util/src/stream/stream/enumerate.rs @@ -20,10 +20,7 @@ impl Enumerate { unsafe_unpinned!(count: usize); pub(super) fn new(stream: St) -> Enumerate { - Enumerate { - stream, - count: 0, - } + Enumerate { stream, count: 0 } } /// Acquires a reference to the underlying stream that this combinator is @@ -68,10 +65,7 @@ impl FusedStream for Enumerate { impl Stream for Enumerate { type Item = (usize, St::Item); - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match ready!(self.as_mut().stream().poll_next(cx)) { Some(item) => { let count = self.count; diff --git a/futures-util/src/stream/stream/filter.rs b/futures-util/src/stream/stream/filter.rs index 06335f1ee0..c40de1cabf 100644 --- a/futures-util/src/stream/stream/filter.rs +++ b/futures-util/src/stream/stream/filter.rs @@ -10,7 +10,8 @@ use pin_utils::{unsafe_pinned, unsafe_unpinned}; /// Stream for the [`filter`](super::StreamExt::filter) method. #[must_use = "streams do nothing unless polled"] pub struct Filter - where St: Stream, +where + St: Stream, { stream: St, f: F, @@ -22,7 +23,8 @@ impl Unpin for Filter where St: Stream + Unpin, Fut: Unpin, -{} +{ +} impl fmt::Debug for Filter where @@ -40,9 +42,10 @@ where } impl Filter -where St: Stream, - F: FnMut(&St::Item) -> Fut, - Fut: Future, +where + St: Stream, + F: FnMut(&St::Item) -> Fut, + Fut: Future, { unsafe_pinned!(stream: St); unsafe_unpinned!(f: F); @@ -50,12 +53,7 @@ where St: Stream, unsafe_unpinned!(pending_item: Option); pub(super) fn new(stream: St, f: F) -> Filter { - Filter { - stream, - f, - pending_fut: None, - pending_item: None, - } + Filter { stream, f, pending_fut: None, pending_item: None } } /// Acquires a reference to the underlying stream that this combinator is @@ -92,9 +90,10 @@ where St: Stream, } impl FusedStream for Filter - where St: Stream + FusedStream, - F: FnMut(&St::Item) -> Fut, - Fut: Future, +where + St: Stream + FusedStream, + F: FnMut(&St::Item) -> Fut, + Fut: Future, { fn is_terminated(&self) -> bool { self.pending_fut.is_none() && self.stream.is_terminated() @@ -102,16 +101,14 @@ impl FusedStream for Filter } impl Stream for Filter - where St: Stream, - F: FnMut(&St::Item) -> Fut, - Fut: Future, +where + St: Stream, + F: FnMut(&St::Item) -> Fut, + Fut: Future, { type Item = St::Item; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { loop { if self.pending_fut.is_none() { let item = match ready!(self.as_mut().stream().poll_next(cx)) { @@ -147,9 +144,10 @@ impl Stream for Filter // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl Sink for Filter - where S: Stream + Sink, - F: FnMut(&S::Item) -> Fut, - Fut: Future, +where + S: Stream + Sink, + F: FnMut(&S::Item) -> Fut, + Fut: Future, { type Error = S::Error; diff --git a/futures-util/src/stream/stream/filter_map.rs b/futures-util/src/stream/stream/filter_map.rs index 532e6cad96..82d2c61266 100644 --- a/futures-util/src/stream/stream/filter_map.rs +++ b/futures-util/src/stream/stream/filter_map.rs @@ -19,7 +19,8 @@ impl Unpin for FilterMap where St: Unpin, Fut: Unpin, -{} +{ +} impl fmt::Debug for FilterMap where @@ -35,9 +36,10 @@ where } impl FilterMap - where St: Stream, - F: FnMut(St::Item) -> Fut, - Fut: Future, +where + St: Stream, + F: FnMut(St::Item) -> Fut, + Fut: Future, { unsafe_pinned!(stream: St); unsafe_unpinned!(f: F); @@ -81,9 +83,10 @@ impl FilterMap } impl FusedStream for FilterMap - where St: Stream + FusedStream, - F: FnMut(St::Item) -> Fut, - Fut: Future>, +where + St: Stream + FusedStream, + F: FnMut(St::Item) -> Fut, + Fut: Future>, { fn is_terminated(&self) -> bool { self.pending.is_none() && self.stream.is_terminated() @@ -91,16 +94,14 @@ impl FusedStream for FilterMap } impl Stream for FilterMap - where St: Stream, - F: FnMut(St::Item) -> Fut, - Fut: Future>, +where + St: Stream, + F: FnMut(St::Item) -> Fut, + Fut: Future>, { type Item = T; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { loop { if self.pending.is_none() { let item = match ready!(self.as_mut().stream().poll_next(cx)) { @@ -133,9 +134,10 @@ impl Stream for FilterMap // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl Sink for FilterMap - where S: Stream + Sink, - F: FnMut(S::Item) -> Fut, - Fut: Future, +where + S: Stream + Sink, + F: FnMut(S::Item) -> Fut, + Fut: Future, { type Error = S::Error; diff --git a/futures-util/src/stream/stream/fold.rs b/futures-util/src/stream/stream/fold.rs index e92a72ed90..55b021b90a 100644 --- a/futures-util/src/stream/stream/fold.rs +++ b/futures-util/src/stream/stream/fold.rs @@ -32,9 +32,10 @@ where } impl Fold -where St: Stream, - F: FnMut(T, St::Item) -> Fut, - Fut: Future, +where + St: Stream, + F: FnMut(T, St::Item) -> Fut, + Fut: Future, { unsafe_pinned!(stream: St); unsafe_unpinned!(f: F); @@ -42,19 +43,15 @@ where St: Stream, unsafe_pinned!(future: Option); pub(super) fn new(stream: St, f: F, t: T) -> Fold { - Fold { - stream, - f, - accum: Some(t), - future: None, - } + Fold { stream, f, accum: Some(t), future: None } } } impl FusedFuture for Fold - where St: Stream, - F: FnMut(T, St::Item) -> Fut, - Fut: Future, +where + St: Stream, + F: FnMut(T, St::Item) -> Fut, + Fut: Future, { fn is_terminated(&self) -> bool { self.accum.is_none() && self.future.is_none() @@ -62,9 +59,10 @@ impl FusedFuture for Fold } impl Future for Fold - where St: Stream, - F: FnMut(T, St::Item) -> Fut, - Fut: Future, +where + St: Stream, + F: FnMut(T, St::Item) -> Fut, + Fut: Future, { type Output = T; @@ -78,14 +76,13 @@ impl Future for Fold } let item = ready!(self.as_mut().stream().poll_next(cx)); - let accum = self.as_mut().accum().take() - .expect("Fold polled after completion"); + let accum = self.as_mut().accum().take().expect("Fold polled after completion"); if let Some(e) = item { let future = (self.as_mut().f())(accum, e); self.as_mut().future().set(Some(future)); } else { - return Poll::Ready(accum) + return Poll::Ready(accum); } } } diff --git a/futures-util/src/stream/stream/for_each.rs b/futures-util/src/stream/stream/for_each.rs index f8adcb2927..a81c8e9b31 100644 --- a/futures-util/src/stream/stream/for_each.rs +++ b/futures-util/src/stream/stream/for_each.rs @@ -17,7 +17,8 @@ impl Unpin for ForEach where St: Unpin, Fut: Unpin, -{} +{ +} impl fmt::Debug for ForEach where @@ -33,27 +34,25 @@ where } impl ForEach -where St: Stream, - F: FnMut(St::Item) -> Fut, - Fut: Future, +where + St: Stream, + F: FnMut(St::Item) -> Fut, + Fut: Future, { unsafe_pinned!(stream: St); unsafe_unpinned!(f: F); unsafe_pinned!(future: Option); pub(super) fn new(stream: St, f: F) -> ForEach { - ForEach { - stream, - f, - future: None, - } + ForEach { stream, f, future: None } } } impl FusedFuture for ForEach - where St: FusedStream, - F: FnMut(St::Item) -> Fut, - Fut: Future, +where + St: FusedStream, + F: FnMut(St::Item) -> Fut, + Fut: Future, { fn is_terminated(&self) -> bool { self.future.is_none() && self.stream.is_terminated() @@ -61,9 +60,10 @@ impl FusedFuture for ForEach } impl Future for ForEach - where St: Stream, - F: FnMut(St::Item) -> Fut, - Fut: Future, +where + St: Stream, + F: FnMut(St::Item) -> Fut, + Fut: Future, { type Output = (); diff --git a/futures-util/src/stream/stream/forward.rs b/futures-util/src/stream/stream/forward.rs index fd89625093..1d3c5473a5 100644 --- a/futures-util/src/stream/stream/forward.rs +++ b/futures-util/src/stream/stream/forward.rs @@ -1,4 +1,4 @@ -use crate::stream::{StreamExt, Fuse}; +use crate::stream::{Fuse, StreamExt}; use core::pin::Pin; use futures_core::future::{FusedFuture, Future}; use futures_core::stream::{Stream, TryStream}; @@ -29,11 +29,7 @@ where unsafe_unpinned!(buffered_item: Option); pub(super) fn new(stream: St, sink: Si) -> Self { - Forward { - sink: Some(sink), - stream: stream.fuse(), - buffered_item: None, - } + Forward { sink: Some(sink), stream: stream.fuse(), buffered_item: None } } fn try_start_send( @@ -70,10 +66,7 @@ where { type Output = Result<(), E>; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { // If we've got an item buffered already, we need to write it to the // sink before we can do anything else if let Some(item) = self.as_mut().buffered_item().take() { @@ -82,16 +75,15 @@ where loop { match self.as_mut().stream().poll_next(cx)? { - Poll::Ready(Some(item)) => - ready!(self.as_mut().try_start_send(cx, item))?, + Poll::Ready(Some(item)) => ready!(self.as_mut().try_start_send(cx, item))?, Poll::Ready(None) => { ready!(self.as_mut().sink().as_pin_mut().expect(INVALID_POLL).poll_close(cx))?; self.as_mut().sink().set(None); - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); } Poll::Pending => { ready!(self.as_mut().sink().as_pin_mut().expect(INVALID_POLL).poll_flush(cx))?; - return Poll::Pending + return Poll::Pending; } } } diff --git a/futures-util/src/stream/stream/fuse.rs b/futures-util/src/stream/stream/fuse.rs index 9085dc553c..6c74c0a639 100644 --- a/futures-util/src/stream/stream/fuse.rs +++ b/futures-util/src/stream/stream/fuse.rs @@ -74,10 +74,7 @@ impl FusedStream for Fuse { impl Stream for Fuse { type Item = S::Item; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if self.done { return Poll::Ready(None); } diff --git a/futures-util/src/stream/stream/inspect.rs b/futures-util/src/stream/stream/inspect.rs index e34970ae65..3ab8b3a937 100644 --- a/futures-util/src/stream/stream/inspect.rs +++ b/futures-util/src/stream/stream/inspect.rs @@ -20,15 +20,14 @@ where St: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Inspect") - .field("stream", &self.stream) - .finish() + f.debug_struct("Inspect").field("stream", &self.stream).finish() } } impl Inspect - where St: Stream, - F: FnMut(&St::Item), +where + St: Stream, + F: FnMut(&St::Item), { unsafe_pinned!(stream: St); unsafe_unpinned!(f: F); @@ -71,8 +70,9 @@ impl Inspect } impl FusedStream for Inspect - where St: FusedStream, - F: FnMut(&St::Item), +where + St: FusedStream, + F: FnMut(&St::Item), { fn is_terminated(&self) -> bool { self.stream.is_terminated() @@ -87,19 +87,14 @@ pub(crate) fn inspect(x: T, mut f: F) -> T { } impl Stream for Inspect - where St: Stream, - F: FnMut(&St::Item), +where + St: Stream, + F: FnMut(&St::Item), { type Item = St::Item; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { - self.as_mut() - .stream() - .poll_next(cx) - .map(|opt| opt.map(|e| inspect(e, self.as_mut().f()))) + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.as_mut().stream().poll_next(cx).map(|opt| opt.map(|e| inspect(e, self.as_mut().f()))) } fn size_hint(&self) -> (usize, Option) { @@ -110,8 +105,9 @@ impl Stream for Inspect // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl Sink for Inspect - where S: Stream + Sink, - F: FnMut(&S::Item), +where + S: Stream + Sink, + F: FnMut(&S::Item), { type Error = S::Error; diff --git a/futures-util/src/stream/stream/into_future.rs b/futures-util/src/stream/stream/into_future.rs index abae98c0c9..48d23e7390 100644 --- a/futures-util/src/stream/stream/into_future.rs +++ b/futures-util/src/stream/stream/into_future.rs @@ -83,10 +83,7 @@ impl FusedFuture for StreamFuture { impl Future for StreamFuture { type Output = (Option, St); - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let item = { let s = self.stream.as_mut().expect("polling StreamFuture twice"); ready!(s.poll_next_unpin(cx)) diff --git a/futures-util/src/stream/stream/map.rs b/futures-util/src/stream/stream/map.rs index 81194342c4..a73263c08e 100644 --- a/futures-util/src/stream/stream/map.rs +++ b/futures-util/src/stream/stream/map.rs @@ -20,15 +20,14 @@ where St: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Map") - .field("stream", &self.stream) - .finish() + f.debug_struct("Map").field("stream", &self.stream).finish() } } impl Map - where St: Stream, - F: FnMut(St::Item) -> T, +where + St: Stream, + F: FnMut(St::Item) -> T, { unsafe_pinned!(stream: St); unsafe_unpinned!(f: F); @@ -71,8 +70,9 @@ impl Map } impl FusedStream for Map - where St: FusedStream, - F: FnMut(St::Item) -> T, +where + St: FusedStream, + F: FnMut(St::Item) -> T, { fn is_terminated(&self) -> bool { self.stream.is_terminated() @@ -80,19 +80,14 @@ impl FusedStream for Map } impl Stream for Map - where St: Stream, - F: FnMut(St::Item) -> T, +where + St: Stream, + F: FnMut(St::Item) -> T, { type Item = T; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { - self.as_mut() - .stream() - .poll_next(cx) - .map(|opt| opt.map(|x| self.as_mut().f()(x))) + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.as_mut().stream().poll_next(cx).map(|opt| opt.map(|x| self.as_mut().f()(x))) } fn size_hint(&self) -> (usize, Option) { @@ -103,8 +98,9 @@ impl Stream for Map // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl Sink for Map - where S: Stream + Sink, - F: FnMut(S::Item) -> T, +where + S: Stream + Sink, + F: FnMut(S::Item) -> T, { type Error = S::Error; diff --git a/futures-util/src/stream/stream/mod.rs b/futures-util/src/stream/stream/mod.rs index da5ade85bb..d0efbfc62f 100644 --- a/futures-util/src/stream/stream/mod.rs +++ b/futures-util/src/stream/stream/mod.rs @@ -544,10 +544,12 @@ pub trait StreamExt: Stream { Flatten::new(self) } - /// Combinator similar to [`StreamExt::fold`] that holds internal state and produces a new stream. + /// Combinator similar to [`StreamExt::fold`] that holds internal state + /// and produces a new stream. /// - /// Accepts initial state and closure which will be applied to each element of the stream until provided closure - /// returns `None`. Once `None` is returned, stream will be terminated. + /// Accepts initial state and closure which will be applied to each element + /// of the stream until provided closure returns `None`. Once `None` is + /// returned, stream will be terminated. /// /// # Examples /// @@ -580,7 +582,7 @@ pub trait StreamExt: Stream { /// /// This function, like `Iterator::skip_while`, will skip elements on the /// stream until the predicate `f` resolves to `false`. Once one element - /// returns false all future elements will be returned from the underlying + /// returns `false`, all future elements will be returned from the underlying /// stream. /// /// # Examples @@ -611,7 +613,7 @@ pub trait StreamExt: Stream { /// /// This function, like `Iterator::take_while`, will take elements from the /// stream until the predicate `f` resolves to `false`. Once one element - /// returns false it will always return that the stream is done. + /// returns `false`, it will always return that the stream is done. /// /// # Examples /// @@ -1117,7 +1119,7 @@ pub trait StreamExt: Stream { Forward::new(self, sink) } - /// Splits this `Stream + Sink` object into separate `Stream` and `Sink` + /// Splits this `Stream + Sink` object into separate `Sink` and `Stream` /// objects. /// /// This can be useful when you want to split ownership between tasks, or diff --git a/futures-util/src/stream/stream/next.rs b/futures-util/src/stream/stream/next.rs index 2d7463213b..1fa74e442a 100644 --- a/futures-util/src/stream/stream/next.rs +++ b/futures-util/src/stream/stream/next.rs @@ -28,10 +28,7 @@ impl FusedFuture for Next<'_, St> { impl Future for Next<'_, St> { type Output = Option; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { self.stream.poll_next_unpin(cx) } } diff --git a/futures-util/src/stream/stream/peek.rs b/futures-util/src/stream/stream/peek.rs index 9272bafe90..c891ca36ee 100644 --- a/futures-util/src/stream/stream/peek.rs +++ b/futures-util/src/stream/stream/peek.rs @@ -28,10 +28,7 @@ impl Peekable { unsafe_unpinned!(peeked: Option); pub(super) fn new(stream: St) -> Peekable { - Peekable { - stream: stream.fuse(), - peeked: None, - } + Peekable { stream: stream.fuse(), peeked: None } } /// Acquires a reference to the underlying stream that this combinator is @@ -100,10 +97,7 @@ impl Peekable { /// /// This method polls the underlying stream and return either a reference /// to the next item if the stream is ready or passes through any errors. - pub fn poll_peek( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + pub fn poll_peek(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match self.do_poll_peek(cx) { Either::Left(_) => Poll::Pending, Either::Right(poll) => Poll::Ready(poll), @@ -164,9 +158,7 @@ where St::Item: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Peek") - .field("inner", &self.inner) - .finish() + f.debug_struct("Peek").field("inner", &self.inner).finish() } } diff --git a/futures-util/src/stream/stream/scan.rs b/futures-util/src/stream/stream/scan.rs index 4f937f4fd9..6cc188a4e8 100644 --- a/futures-util/src/stream/stream/scan.rs +++ b/futures-util/src/stream/stream/scan.rs @@ -57,14 +57,7 @@ where Fut: Future>, { pub(super) fn new(stream: St, initial_state: S, f: F) -> Scan { - Scan { - stream, - state_f: Some(StateFn { - state: initial_state, - f, - }), - future: None, - } + Scan { stream, state_f: Some(StateFn { state: initial_state, f }), future: None } } /// Acquires a reference to the underlying stream that this combinator is diff --git a/futures-util/src/stream/stream/select_next_some.rs b/futures-util/src/stream/stream/select_next_some.rs index 884f252769..8b62a43999 100644 --- a/futures-util/src/stream/stream/select_next_some.rs +++ b/futures-util/src/stream/stream/select_next_some.rs @@ -1,8 +1,8 @@ +use crate::stream::StreamExt; use core::pin::Pin; +use futures_core::future::{FusedFuture, Future}; use futures_core::stream::FusedStream; -use futures_core::future::{Future, FusedFuture}; use futures_core::task::{Context, Poll}; -use crate::stream::StreamExt; /// Future for the [`select_next_some`](super::StreamExt::select_next_some) /// method. diff --git a/futures-util/src/stream/stream/skip.rs b/futures-util/src/stream/stream/skip.rs index 0b7c632daf..b228399009 100644 --- a/futures-util/src/stream/stream/skip.rs +++ b/futures-util/src/stream/stream/skip.rs @@ -20,10 +20,7 @@ impl Skip { unsafe_unpinned!(remaining: usize); pub(super) fn new(stream: St, n: usize) -> Skip { - Skip { - stream, - remaining: n, - } + Skip { stream, remaining: n } } /// Acquires a reference to the underlying stream that this combinator is @@ -68,10 +65,7 @@ impl FusedStream for Skip { impl Stream for Skip { type Item = St::Item; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { while self.remaining > 0 { match ready!(self.as_mut().stream().poll_next(cx)) { Some(_) => *self.as_mut().remaining() -= 1, diff --git a/futures-util/src/stream/stream/skip_while.rs b/futures-util/src/stream/stream/skip_while.rs index 666d9deabc..dd9fe1b8fb 100644 --- a/futures-util/src/stream/stream/skip_while.rs +++ b/futures-util/src/stream/stream/skip_while.rs @@ -9,7 +9,10 @@ use pin_utils::{unsafe_pinned, unsafe_unpinned}; /// Stream for the [`skip_while`](super::StreamExt::skip_while) method. #[must_use = "streams do nothing unless polled"] -pub struct SkipWhile where St: Stream { +pub struct SkipWhile +where + St: Stream, +{ stream: St, f: F, pending_fut: Option, @@ -36,9 +39,10 @@ where } impl SkipWhile - where St: Stream, - F: FnMut(&St::Item) -> Fut, - Fut: Future, +where + St: Stream, + F: FnMut(&St::Item) -> Fut, + Fut: Future, { unsafe_pinned!(stream: St); unsafe_unpinned!(f: F); @@ -47,13 +51,7 @@ impl SkipWhile unsafe_unpinned!(done_skipping: bool); pub(super) fn new(stream: St, f: F) -> SkipWhile { - SkipWhile { - stream, - f, - pending_fut: None, - pending_item: None, - done_skipping: false, - } + SkipWhile { stream, f, pending_fut: None, pending_item: None, done_skipping: false } } /// Acquires a reference to the underlying stream that this combinator is @@ -90,9 +88,10 @@ impl SkipWhile } impl FusedStream for SkipWhile - where St: FusedStream, - F: FnMut(&St::Item) -> Fut, - Fut: Future, +where + St: FusedStream, + F: FnMut(&St::Item) -> Fut, + Fut: Future, { fn is_terminated(&self) -> bool { self.pending_item.is_none() && self.stream.is_terminated() @@ -100,16 +99,14 @@ impl FusedStream for SkipWhile } impl Stream for SkipWhile - where St: Stream, - F: FnMut(&St::Item) -> Fut, - Fut: Future, +where + St: Stream, + F: FnMut(&St::Item) -> Fut, + Fut: Future, { type Item = St::Item; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if self.done_skipping { return self.as_mut().stream().poll_next(cx); } @@ -131,7 +128,7 @@ impl Stream for SkipWhile if !skipped { *self.as_mut().done_skipping() = true; - return Poll::Ready(Some(item)) + return Poll::Ready(Some(item)); } } } @@ -150,9 +147,10 @@ impl Stream for SkipWhile // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl Sink for SkipWhile - where S: Stream + Sink, - F: FnMut(&S::Item) -> Fut, - Fut: Future, +where + S: Stream + Sink, + F: FnMut(&S::Item) -> Fut, + Fut: Future, { type Error = S::Error; diff --git a/futures-util/src/stream/stream/take.rs b/futures-util/src/stream/stream/take.rs index 1109a4a0f0..edf865ef08 100644 --- a/futures-util/src/stream/stream/take.rs +++ b/futures-util/src/stream/stream/take.rs @@ -1,6 +1,6 @@ use core::cmp; use core::pin::Pin; -use futures_core::stream::{Stream, FusedStream}; +use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; @@ -21,10 +21,7 @@ impl Take { unsafe_unpinned!(remaining: usize); pub(super) fn new(stream: St, n: usize) -> Take { - Take { - stream, - remaining: n, - } + Take { stream, remaining: n } } /// Acquires a reference to the underlying stream that this combinator is @@ -61,14 +58,12 @@ impl Take { } impl Stream for Take - where St: Stream, +where + St: Stream, { type Item = St::Item; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if self.remaining == 0 { Poll::Ready(None) } else { @@ -92,7 +87,7 @@ impl Stream for Take let upper = match upper { Some(x) if x < self.remaining as usize => Some(x), - _ => Some(self.remaining as usize) + _ => Some(self.remaining as usize), }; (lower, upper) @@ -100,7 +95,8 @@ impl Stream for Take } impl FusedStream for Take - where St: FusedStream, +where + St: FusedStream, { fn is_terminated(&self) -> bool { self.remaining == 0 || self.stream.is_terminated() @@ -110,7 +106,8 @@ impl FusedStream for Take // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl Sink for Take - where S: Stream + Sink, +where + S: Stream + Sink, { type Error = S::Error; diff --git a/futures-util/src/stream/stream/take_while.rs b/futures-util/src/stream/stream/take_while.rs index 68606ec263..8efeff30f3 100644 --- a/futures-util/src/stream/stream/take_while.rs +++ b/futures-util/src/stream/stream/take_while.rs @@ -1,7 +1,7 @@ use core::fmt; use core::pin::Pin; use futures_core::future::Future; -use futures_core::stream::{Stream, FusedStream}; +use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; @@ -9,7 +9,7 @@ use pin_utils::{unsafe_pinned, unsafe_unpinned}; /// Stream for the [`take_while`](super::StreamExt::take_while) method. #[must_use = "streams do nothing unless polled"] -pub struct TakeWhile { +pub struct TakeWhile { stream: St, f: F, pending_fut: Option, @@ -44,18 +44,13 @@ impl TakeWhile { } impl TakeWhile - where St: Stream, - F: FnMut(&St::Item) -> Fut, - Fut: Future, +where + St: Stream, + F: FnMut(&St::Item) -> Fut, + Fut: Future, { pub(super) fn new(stream: St, f: F) -> TakeWhile { - TakeWhile { - stream, - f, - pending_fut: None, - pending_item: None, - done_taking: false, - } + TakeWhile { stream, f, pending_fut: None, pending_item: None, done_taking: false } } /// Acquires a reference to the underlying stream that this combinator is @@ -92,16 +87,14 @@ impl TakeWhile } impl Stream for TakeWhile - where St: Stream, - F: FnMut(&St::Item) -> Fut, - Fut: Future, +where + St: Stream, + F: FnMut(&St::Item) -> Fut, + Fut: Future, { type Item = St::Item; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if self.done_taking { return Poll::Ready(None); } @@ -144,9 +137,10 @@ impl Stream for TakeWhile } impl FusedStream for TakeWhile - where St: FusedStream, - F: FnMut(&St::Item) -> Fut, - Fut: Future, +where + St: FusedStream, + F: FnMut(&St::Item) -> Fut, + Fut: Future, { fn is_terminated(&self) -> bool { self.done_taking || self.pending_item.is_none() && self.stream.is_terminated() @@ -156,7 +150,8 @@ impl FusedStream for TakeWhile // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl Sink for TakeWhile - where S: Stream + Sink, +where + S: Stream + Sink, { type Error = S::Error; diff --git a/futures-util/src/stream/stream/then.rs b/futures-util/src/stream/stream/then.rs index 39843b2504..c8e9264176 100644 --- a/futures-util/src/stream/stream/then.rs +++ b/futures-util/src/stream/stream/then.rs @@ -23,10 +23,7 @@ where Fut: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Then") - .field("stream", &self.stream) - .field("future", &self.future) - .finish() + f.debug_struct("Then").field("stream", &self.stream).field("future", &self.future).finish() } } @@ -37,15 +34,12 @@ impl Then { } impl Then - where St: Stream, - F: FnMut(St::Item) -> Fut, +where + St: Stream, + F: FnMut(St::Item) -> Fut, { pub(super) fn new(stream: St, f: F) -> Then { - Then { - stream, - future: None, - f, - } + Then { stream, future: None, f } } /// Acquires a reference to the underlying stream that this combinator is @@ -82,9 +76,10 @@ impl Then } impl FusedStream for Then - where St: FusedStream, - F: FnMut(St::Item) -> Fut, - Fut: Future, +where + St: FusedStream, + F: FnMut(St::Item) -> Fut, + Fut: Future, { fn is_terminated(&self) -> bool { self.future.is_none() && self.stream.is_terminated() @@ -92,16 +87,14 @@ impl FusedStream for Then } impl Stream for Then - where St: Stream, - F: FnMut(St::Item) -> Fut, - Fut: Future, +where + St: Stream, + F: FnMut(St::Item) -> Fut, + Fut: Future, { type Item = Fut::Output; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if self.future.is_none() { let item = match ready!(self.as_mut().stream().poll_next(cx)) { None => return Poll::Ready(None), @@ -131,7 +124,8 @@ impl Stream for Then // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl Sink for Then - where S: Sink, +where + S: Sink, { type Error = S::Error; diff --git a/futures-util/src/stream/stream/zip.rs b/futures-util/src/stream/stream/zip.rs index f97ac17d35..4acd1ee09c 100644 --- a/futures-util/src/stream/stream/zip.rs +++ b/futures-util/src/stream/stream/zip.rs @@ -1,4 +1,4 @@ -use crate::stream::{StreamExt, Fuse}; +use crate::stream::{Fuse, StreamExt}; use core::cmp; use core::pin::Pin; use futures_core::stream::{FusedStream, Stream}; @@ -22,7 +22,8 @@ where Fuse: Unpin, St2: Stream, Fuse: Unpin, -{} +{ +} impl Zip { unsafe_pinned!(stream1: Fuse); @@ -31,12 +32,7 @@ impl Zip { unsafe_unpinned!(queued2: Option); pub(super) fn new(stream1: St1, stream2: St2) -> Zip { - Zip { - stream1: stream1.fuse(), - stream2: stream2.fuse(), - queued1: None, - queued2: None, - } + Zip { stream1: stream1.fuse(), stream2: stream2.fuse(), queued1: None, queued2: None } } /// Acquires a reference to the underlying streams that this combinator is @@ -76,7 +72,9 @@ impl Zip { } impl FusedStream for Zip - where St1: Stream, St2: Stream, +where + St1: Stream, + St2: Stream, { fn is_terminated(&self) -> bool { self.stream1.is_terminated() && self.stream2.is_terminated() @@ -84,14 +82,13 @@ impl FusedStream for Zip } impl Stream for Zip - where St1: Stream, St2: Stream +where + St1: Stream, + St2: Stream, { type Item = (St1::Item, St2::Item); - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if self.queued1.is_none() { match self.as_mut().stream1().poll_next(cx) { Poll::Ready(Some(item1)) => *self.as_mut().queued1() = Some(item1), @@ -106,8 +103,8 @@ impl Stream for Zip } if self.queued1.is_some() && self.queued2.is_some() { - let pair = (self.as_mut().queued1().take().unwrap(), - self.as_mut().queued2().take().unwrap()); + let pair = + (self.as_mut().queued1().take().unwrap(), self.as_mut().queued2().take().unwrap()); Poll::Ready(Some(pair)) } else if self.stream1.is_done() || self.stream2.is_done() { Poll::Ready(None) @@ -135,7 +132,7 @@ impl Stream for Zip } (Some(x), None) => x.checked_add(queued1_len), (None, Some(y)) => y.checked_add(queued2_len), - (None, None) => None + (None, None) => None, }; (lower, upper) diff --git a/futures-util/src/stream/try_stream/and_then.rs b/futures-util/src/stream/try_stream/and_then.rs index 809c32a94b..d133971b3b 100644 --- a/futures-util/src/stream/try_stream/and_then.rs +++ b/futures-util/src/stream/try_stream/and_then.rs @@ -1,7 +1,7 @@ use core::fmt; use core::pin::Pin; use futures_core::future::TryFuture; -use futures_core::stream::{Stream, TryStream, FusedStream}; +use futures_core::stream::{FusedStream, Stream, TryStream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; @@ -37,9 +37,10 @@ impl AndThen { } impl AndThen - where St: TryStream, - F: FnMut(St::Ok) -> Fut, - Fut: TryFuture, +where + St: TryStream, + F: FnMut(St::Ok) -> Fut, + Fut: TryFuture, { pub(super) fn new(stream: St, f: F) -> Self { Self { stream, future: None, f } @@ -79,16 +80,14 @@ impl AndThen } impl Stream for AndThen - where St: TryStream, - F: FnMut(St::Ok) -> Fut, - Fut: TryFuture, +where + St: TryStream, + F: FnMut(St::Ok) -> Fut, + Fut: TryFuture, { type Item = Result; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if self.future.is_none() { let item = match ready!(self.as_mut().stream().try_poll_next(cx)?) { None => return Poll::Ready(None), @@ -116,9 +115,10 @@ impl Stream for AndThen } impl FusedStream for AndThen - where St: TryStream + FusedStream, - F: FnMut(St::Ok) -> Fut, - Fut: TryFuture, +where + St: TryStream + FusedStream, + F: FnMut(St::Ok) -> Fut, + Fut: TryFuture, { fn is_terminated(&self) -> bool { self.future.is_none() && self.stream.is_terminated() @@ -128,7 +128,8 @@ impl FusedStream for AndThen // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl Sink for AndThen - where S: Sink, +where + S: Sink, { type Error = S::Error; diff --git a/futures-util/src/stream/try_stream/err_into.rs b/futures-util/src/stream/try_stream/err_into.rs index f5d92945f3..f16a348523 100644 --- a/futures-util/src/stream/try_stream/err_into.rs +++ b/futures-util/src/stream/try_stream/err_into.rs @@ -73,12 +73,8 @@ where { type Item = Result; - fn poll_next( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { - self.stream().try_poll_next(cx) - .map(|res| res.map(|some| some.map_err(Into::into))) + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.stream().try_poll_next(cx).map(|res| res.map(|some| some.map_err(Into::into))) } fn size_hint(&self) -> (usize, Option) { diff --git a/futures-util/src/stream/try_stream/inspect_err.rs b/futures-util/src/stream/try_stream/inspect_err.rs index 3c23ae0395..a7cb664b26 100644 --- a/futures-util/src/stream/try_stream/inspect_err.rs +++ b/futures-util/src/stream/try_stream/inspect_err.rs @@ -21,9 +21,7 @@ where St: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("InspectErr") - .field("stream", &self.stream) - .finish() + f.debug_struct("InspectErr").field("stream", &self.stream).finish() } } @@ -91,10 +89,7 @@ where { type Item = Result; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.as_mut() .stream() .try_poll_next(cx) diff --git a/futures-util/src/stream/try_stream/inspect_ok.rs b/futures-util/src/stream/try_stream/inspect_ok.rs index 89fb459be9..6d69fec14b 100644 --- a/futures-util/src/stream/try_stream/inspect_ok.rs +++ b/futures-util/src/stream/try_stream/inspect_ok.rs @@ -21,9 +21,7 @@ where St: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("InspectOk") - .field("stream", &self.stream) - .finish() + f.debug_struct("InspectOk").field("stream", &self.stream).finish() } } @@ -91,10 +89,7 @@ where { type Item = Result; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.as_mut() .stream() .try_poll_next(cx) diff --git a/futures-util/src/stream/try_stream/into_async_read.rs b/futures-util/src/stream/try_stream/into_async_read.rs index 71bbfd1c72..66b2da1b6f 100644 --- a/futures-util/src/stream/try_stream/into_async_read.rs +++ b/futures-util/src/stream/try_stream/into_async_read.rs @@ -2,7 +2,7 @@ use crate::stream::TryStreamExt; use core::pin::Pin; use futures_core::stream::TryStream; use futures_core::task::{Context, Poll}; -use futures_io::{AsyncRead, AsyncWrite, AsyncBufRead}; +use futures_io::{AsyncBufRead, AsyncRead, AsyncWrite}; use std::cmp; use std::io::{Error, Result}; @@ -38,10 +38,7 @@ where St::Ok: AsRef<[u8]>, { pub(super) fn new(stream: St) -> Self { - IntoAsyncRead { - stream, - state: ReadState::PendingChunk, - } + IntoAsyncRead { stream, state: ReadState::PendingChunk } } } @@ -61,9 +58,7 @@ where let chunk = chunk.as_ref(); let len = cmp::min(buf.len(), chunk.len() - *chunk_start); - buf[..len].copy_from_slice( - &chunk[*chunk_start..*chunk_start + len], - ); + buf[..len].copy_from_slice(&chunk[*chunk_start..*chunk_start + len]); *chunk_start += len; if chunk.len() == *chunk_start { @@ -72,26 +67,21 @@ where return Poll::Ready(Ok(len)); } - ReadState::PendingChunk => { - match ready!(self.stream.try_poll_next_unpin(cx)) { - Some(Ok(chunk)) => { - if !chunk.as_ref().is_empty() { - self.state = ReadState::Ready { - chunk, - chunk_start: 0, - }; - } - } - Some(Err(err)) => { - self.state = ReadState::Eof; - return Poll::Ready(Err(err)); - } - None => { - self.state = ReadState::Eof; - return Poll::Ready(Ok(0)); + ReadState::PendingChunk => match ready!(self.stream.try_poll_next_unpin(cx)) { + Some(Ok(chunk)) => { + if !chunk.as_ref().is_empty() { + self.state = ReadState::Ready { chunk, chunk_start: 0 }; } } - } + Some(Err(err)) => { + self.state = ReadState::Eof; + return Poll::Ready(Err(err)); + } + None => { + self.state = ReadState::Eof; + return Poll::Ready(Ok(0)); + } + }, ReadState::Eof => { return Poll::Ready(Ok(0)); } @@ -108,23 +98,17 @@ where fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, - buf: &[u8] + buf: &[u8], ) -> Poll> { - Pin::new( &mut self.stream ).poll_write( cx, buf ) + Pin::new(&mut self.stream).poll_write(cx, buf) } - fn poll_flush( - mut self: Pin<&mut Self>, - cx: &mut Context<'_> - ) -> Poll> { - Pin::new( &mut self.stream ).poll_flush( cx ) + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.stream).poll_flush(cx) } - fn poll_close( - mut self: Pin<&mut Self>, - cx: &mut Context<'_> - ) -> Poll> { - Pin::new( &mut self.stream ).poll_close( cx ) + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.stream).poll_close(cx) } } @@ -133,18 +117,12 @@ where St: TryStream + Unpin, St::Ok: AsRef<[u8]>, { - fn poll_fill_buf( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_fill_buf(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { while let ReadState::PendingChunk = self.state { match ready!(self.stream.try_poll_next_unpin(cx)) { Some(Ok(chunk)) => { if !chunk.as_ref().is_empty() { - self.state = ReadState::Ready { - chunk, - chunk_start: 0, - }; + self.state = ReadState::Ready { chunk, chunk_start: 0 }; } } Some(Err(err)) => { @@ -167,12 +145,11 @@ where Poll::Ready(Ok(&[])) } - fn consume( - mut self: Pin<&mut Self>, - amount: usize, - ) { - // https://github.com/rust-lang/futures-rs/pull/1556#discussion_r281644295 - if amount == 0 { return } + fn consume(mut self: Pin<&mut Self>, amount: usize) { + // https://github.com/rust-lang/futures-rs/pull/1556#discussion_r281644295 + if amount == 0 { + return; + } if let ReadState::Ready { chunk, chunk_start } = &mut self.state { *chunk_start += amount; debug_assert!(*chunk_start <= chunk.as_ref().len()); diff --git a/futures-util/src/stream/try_stream/into_stream.rs b/futures-util/src/stream/try_stream/into_stream.rs index b0fa07aa79..02c37e6625 100644 --- a/futures-util/src/stream/try_stream/into_stream.rs +++ b/futures-util/src/stream/try_stream/into_stream.rs @@ -63,10 +63,7 @@ impl Stream for IntoStream { type Item = Result; #[inline] - fn poll_next( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.stream().try_poll_next(cx) } diff --git a/futures-util/src/stream/try_stream/map_err.rs b/futures-util/src/stream/try_stream/map_err.rs index 1b98d6b4bc..f82bb92557 100644 --- a/futures-util/src/stream/try_stream/map_err.rs +++ b/futures-util/src/stream/try_stream/map_err.rs @@ -20,9 +20,7 @@ where St: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("MapErr") - .field("stream", &self.stream) - .finish() + f.debug_struct("MapErr").field("stream", &self.stream).finish() } } @@ -85,10 +83,7 @@ where { type Item = Result; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.as_mut() .stream() .try_poll_next(cx) diff --git a/futures-util/src/stream/try_stream/map_ok.rs b/futures-util/src/stream/try_stream/map_ok.rs index 19d01be459..5c51e2a3a9 100644 --- a/futures-util/src/stream/try_stream/map_ok.rs +++ b/futures-util/src/stream/try_stream/map_ok.rs @@ -20,9 +20,7 @@ where St: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("MapOk") - .field("stream", &self.stream) - .finish() + f.debug_struct("MapOk").field("stream", &self.stream).finish() } } @@ -85,10 +83,7 @@ where { type Item = Result; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.as_mut() .stream() .try_poll_next(cx) diff --git a/futures-util/src/stream/try_stream/mod.rs b/futures-util/src/stream/try_stream/mod.rs index 6a7ced4f8c..45a57ed7d1 100644 --- a/futures-util/src/stream/try_stream/mod.rs +++ b/futures-util/src/stream/try_stream/mod.rs @@ -385,8 +385,9 @@ pub trait TryStreamExt: TryStream { /// Skip elements on this stream while the provided asynchronous predicate /// resolves to `true`. /// - /// This function is similar to [`StreamExt::skip_while`](crate::stream::StreamExt::skip_while) - /// but exits early if an error occurs. + /// This function is similar to + /// [`StreamExt::skip_while`](crate::stream::StreamExt::skip_while) but exits + /// early if an error occurs. /// /// # Examples /// diff --git a/futures-util/src/stream/try_stream/or_else.rs b/futures-util/src/stream/try_stream/or_else.rs index 33310d1ce3..722e0e35d2 100644 --- a/futures-util/src/stream/try_stream/or_else.rs +++ b/futures-util/src/stream/try_stream/or_else.rs @@ -1,7 +1,7 @@ use core::fmt; use core::pin::Pin; use futures_core::future::TryFuture; -use futures_core::stream::{Stream, TryStream, FusedStream}; +use futures_core::stream::{FusedStream, Stream, TryStream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; @@ -37,9 +37,10 @@ impl OrElse { } impl OrElse - where St: TryStream, - F: FnMut(St::Error) -> Fut, - Fut: TryFuture, +where + St: TryStream, + F: FnMut(St::Error) -> Fut, + Fut: TryFuture, { pub(super) fn new(stream: St, f: F) -> Self { Self { stream, future: None, f } @@ -79,16 +80,14 @@ impl OrElse } impl Stream for OrElse - where St: TryStream, - F: FnMut(St::Error) -> Fut, - Fut: TryFuture, +where + St: TryStream, + F: FnMut(St::Error) -> Fut, + Fut: TryFuture, { type Item = Result; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if self.future.is_none() { let item = match ready!(self.as_mut().stream().try_poll_next(cx)) { None => return Poll::Ready(None), @@ -117,9 +116,10 @@ impl Stream for OrElse } impl FusedStream for OrElse - where St: TryStream + FusedStream, - F: FnMut(St::Error) -> Fut, - Fut: TryFuture, +where + St: TryStream + FusedStream, + F: FnMut(St::Error) -> Fut, + Fut: TryFuture, { fn is_terminated(&self) -> bool { self.future.is_none() && self.stream.is_terminated() @@ -129,7 +129,8 @@ impl FusedStream for OrElse // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl Sink for OrElse - where S: Sink, +where + S: Sink, { type Error = S::Error; diff --git a/futures-util/src/stream/try_stream/try_collect.rs b/futures-util/src/stream/try_stream/try_collect.rs index d22e8e8543..8e34175ad6 100644 --- a/futures-util/src/stream/try_stream/try_collect.rs +++ b/futures-util/src/stream/try_stream/try_collect.rs @@ -18,10 +18,7 @@ impl TryCollect { unsafe_unpinned!(items: C); pub(super) fn new(s: St) -> TryCollect { - TryCollect { - stream: s, - items: Default::default(), - } + TryCollect { stream: s, items: Default::default() } } fn finish(self: Pin<&mut Self>) -> C { @@ -48,10 +45,7 @@ where { type Output = Result; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { loop { match ready!(self.as_mut().stream().try_poll_next(cx)?) { Some(x) => self.as_mut().items().extend(Some(x)), diff --git a/futures-util/src/stream/try_stream/try_concat.rs b/futures-util/src/stream/try_stream/try_concat.rs index 395f166c6b..17a6fee8f7 100644 --- a/futures-util/src/stream/try_stream/try_concat.rs +++ b/futures-util/src/stream/try_stream/try_concat.rs @@ -23,10 +23,7 @@ where unsafe_unpinned!(accum: Option); pub(super) fn new(stream: St) -> TryConcat { - TryConcat { - stream, - accum: None, - } + TryConcat { stream, accum: None } } } @@ -47,10 +44,8 @@ where } else { *accum = Some(x) } - }, - None => { - return Poll::Ready(Ok(self.as_mut().accum().take().unwrap_or_default())) } + None => return Poll::Ready(Ok(self.as_mut().accum().take().unwrap_or_default())), } } } diff --git a/futures-util/src/stream/try_stream/try_filter.rs b/futures-util/src/stream/try_stream/try_filter.rs index 24a9c3275a..3b2d43b65b 100644 --- a/futures-util/src/stream/try_stream/try_filter.rs +++ b/futures-util/src/stream/try_stream/try_filter.rs @@ -1,7 +1,7 @@ use core::fmt; use core::pin::Pin; use futures_core::future::Future; -use futures_core::stream::{Stream, TryStream, FusedStream}; +use futures_core::stream::{FusedStream, Stream, TryStream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; @@ -11,7 +11,8 @@ use pin_utils::{unsafe_pinned, unsafe_unpinned}; /// method. #[must_use = "streams do nothing unless polled"] pub struct TryFilter - where St: TryStream +where + St: TryStream, { stream: St, f: F, @@ -20,8 +21,11 @@ pub struct TryFilter } impl Unpin for TryFilter - where St: TryStream + Unpin, Fut: Unpin, -{} +where + St: TryStream + Unpin, + Fut: Unpin, +{ +} impl fmt::Debug for TryFilter where @@ -39,7 +43,8 @@ where } impl TryFilter - where St: TryStream +where + St: TryStream, { unsafe_pinned!(stream: St); unsafe_unpinned!(f: F); @@ -47,12 +52,7 @@ impl TryFilter unsafe_unpinned!(pending_item: Option); pub(super) fn new(stream: St, f: F) -> Self { - TryFilter { - stream, - f, - pending_fut: None, - pending_item: None, - } + TryFilter { stream, f, pending_fut: None, pending_item: None } } /// Acquires a reference to the underlying stream that this combinator is @@ -89,9 +89,10 @@ impl TryFilter } impl FusedStream for TryFilter - where St: TryStream + FusedStream, - F: FnMut(&St::Ok) -> Fut, - Fut: Future, +where + St: TryStream + FusedStream, + F: FnMut(&St::Ok) -> Fut, + Fut: Future, { fn is_terminated(&self) -> bool { self.pending_fut.is_none() && self.stream.is_terminated() @@ -99,9 +100,10 @@ impl FusedStream for TryFilter } impl Stream for TryFilter - where St: TryStream, - Fut: Future, - F: FnMut(&St::Ok) -> Fut, +where + St: TryStream, + Fut: Future, + F: FnMut(&St::Ok) -> Fut, { type Item = Result; @@ -144,7 +146,8 @@ impl Stream for TryFilter // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl Sink for TryFilter - where S: TryStream + Sink, +where + S: TryStream + Sink, { type Error = E; diff --git a/futures-util/src/stream/try_stream/try_filter_map.rs b/futures-util/src/stream/try_stream/try_filter_map.rs index ed7eeb227e..83624abd02 100644 --- a/futures-util/src/stream/try_stream/try_filter_map.rs +++ b/futures-util/src/stream/try_stream/try_filter_map.rs @@ -1,7 +1,7 @@ use core::fmt; use core::pin::Pin; -use futures_core::future::{TryFuture}; -use futures_core::stream::{Stream, TryStream, FusedStream}; +use futures_core::future::TryFuture; +use futures_core::stream::{FusedStream, Stream, TryStream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; @@ -17,8 +17,11 @@ pub struct TryFilterMap { } impl Unpin for TryFilterMap - where St: Unpin, Fut: Unpin, -{} +where + St: Unpin, + Fut: Unpin, +{ +} impl fmt::Debug for TryFilterMap where @@ -76,9 +79,10 @@ impl TryFilterMap { } impl FusedStream for TryFilterMap - where St: TryStream + FusedStream, - Fut: TryFuture, Error = St::Error>, - F: FnMut(St::Ok) -> Fut, +where + St: TryStream + FusedStream, + Fut: TryFuture, Error = St::Error>, + F: FnMut(St::Ok) -> Fut, { fn is_terminated(&self) -> bool { self.pending.is_none() && self.stream.is_terminated() @@ -86,9 +90,10 @@ impl FusedStream for TryFilterMap } impl Stream for TryFilterMap - where St: TryStream, - Fut: TryFuture, Error = St::Error>, - F: FnMut(St::Ok) -> Fut, +where + St: TryStream, + Fut: TryFuture, Error = St::Error>, + F: FnMut(St::Ok) -> Fut, { type Item = Result; @@ -128,7 +133,8 @@ impl Stream for TryFilterMap // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl Sink for TryFilterMap - where S: Sink, +where + S: Sink, { type Error = S::Error; diff --git a/futures-util/src/stream/try_stream/try_flatten.rs b/futures-util/src/stream/try_stream/try_flatten.rs index 5f81b22b4c..3982c22e7c 100644 --- a/futures-util/src/stream/try_stream/try_flatten.rs +++ b/futures-util/src/stream/try_stream/try_flatten.rs @@ -102,12 +102,8 @@ where } } - if let Some(item) = ready!(self - .as_mut() - .next() - .as_pin_mut() - .unwrap() - .try_poll_next(cx)?) + if let Some(item) = + ready!(self.as_mut().next().as_pin_mut().unwrap().try_poll_next(cx)?) { return Poll::Ready(Some(Ok(item))); } else { diff --git a/futures-util/src/stream/try_stream/try_fold.rs b/futures-util/src/stream/try_stream/try_fold.rs index b8b8dc24f1..8fa40bf9d2 100644 --- a/futures-util/src/stream/try_stream/try_fold.rs +++ b/futures-util/src/stream/try_stream/try_fold.rs @@ -32,9 +32,10 @@ where } impl TryFold -where St: TryStream, - F: FnMut(T, St::Ok) -> Fut, - Fut: TryFuture, +where + St: TryStream, + F: FnMut(T, St::Ok) -> Fut, + Fut: TryFuture, { unsafe_pinned!(stream: St); unsafe_unpinned!(f: F); @@ -42,19 +43,15 @@ where St: TryStream, unsafe_pinned!(future: Option); pub(super) fn new(stream: St, f: F, t: T) -> TryFold { - TryFold { - stream, - f, - accum: Some(t), - future: None, - } + TryFold { stream, f, accum: Some(t), future: None } } } impl FusedFuture for TryFold - where St: TryStream, - F: FnMut(T, St::Ok) -> Fut, - Fut: TryFuture, +where + St: TryStream, + F: FnMut(T, St::Ok) -> Fut, + Fut: TryFuture, { fn is_terminated(&self) -> bool { self.accum.is_none() && self.future.is_none() @@ -62,9 +59,10 @@ impl FusedFuture for TryFold } impl Future for TryFold - where St: TryStream, - F: FnMut(T, St::Ok) -> Fut, - Fut: TryFuture, +where + St: TryStream, + F: FnMut(T, St::Ok) -> Fut, + Fut: TryFuture, { type Output = Result; @@ -72,11 +70,13 @@ impl Future for TryFold loop { // we're currently processing a future to produce a new accum value if self.accum.is_none() { - let accum = match ready!( - self.as_mut().future().as_pin_mut() - .expect("TryFold polled after completion") - .try_poll(cx) - ) { + let accum = match ready!(self + .as_mut() + .future() + .as_pin_mut() + .expect("TryFold polled after completion") + .try_poll(cx)) + { Ok(accum) => accum, Err(e) => { // Indicate that the future can no longer be polled. @@ -103,7 +103,7 @@ impl Future for TryFold let future = (self.as_mut().f())(accum, e); self.as_mut().future().set(Some(future)); } else { - return Poll::Ready(Ok(accum)) + return Poll::Ready(Ok(accum)); } } } diff --git a/futures-util/src/stream/try_stream/try_for_each.rs b/futures-util/src/stream/try_stream/try_for_each.rs index 2c71107646..c59e11bbd6 100644 --- a/futures-util/src/stream/try_stream/try_for_each.rs +++ b/futures-util/src/stream/try_stream/try_for_each.rs @@ -29,27 +29,25 @@ where } impl TryForEach -where St: TryStream, - F: FnMut(St::Ok) -> Fut, - Fut: TryFuture, +where + St: TryStream, + F: FnMut(St::Ok) -> Fut, + Fut: TryFuture, { unsafe_pinned!(stream: St); unsafe_unpinned!(f: F); unsafe_pinned!(future: Option); pub(super) fn new(stream: St, f: F) -> TryForEach { - TryForEach { - stream, - f, - future: None, - } + TryForEach { stream, f, future: None } } } impl Future for TryForEach - where St: TryStream, - F: FnMut(St::Ok) -> Fut, - Fut: TryFuture, +where + St: TryStream, + F: FnMut(St::Ok) -> Fut, + Fut: TryFuture, { type Output = Result<(), St::Error>; diff --git a/futures-util/src/stream/try_stream/try_next.rs b/futures-util/src/stream/try_stream/try_next.rs index 78599ad109..45b02238c0 100644 --- a/futures-util/src/stream/try_stream/try_next.rs +++ b/futures-util/src/stream/try_stream/try_next.rs @@ -28,10 +28,7 @@ impl FusedFuture for TryNext<'_, S impl Future for TryNext<'_, St> { type Output = Result, St::Error>; - fn poll( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { self.stream.try_poll_next_unpin(cx)?.map(Ok) } } diff --git a/futures-util/src/stream/try_stream/try_skip_while.rs b/futures-util/src/stream/try_stream/try_skip_while.rs index a3d6803a1b..c2c5558526 100644 --- a/futures-util/src/stream/try_stream/try_skip_while.rs +++ b/futures-util/src/stream/try_stream/try_skip_while.rs @@ -1,7 +1,7 @@ use core::fmt; use core::pin::Pin; use futures_core::future::TryFuture; -use futures_core::stream::{Stream, TryStream, FusedStream}; +use futures_core::stream::{FusedStream, Stream, TryStream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; @@ -10,7 +10,10 @@ use pin_utils::{unsafe_pinned, unsafe_unpinned}; /// Stream for the [`try_skip_while`](super::TryStreamExt::try_skip_while) /// method. #[must_use = "streams do nothing unless polled"] -pub struct TrySkipWhile where St: TryStream { +pub struct TrySkipWhile +where + St: TryStream, +{ stream: St, f: F, pending_fut: Option, @@ -37,15 +40,17 @@ where } impl TrySkipWhile - where St: TryStream, +where + St: TryStream, { unsafe_pinned!(stream: St); } impl TrySkipWhile - where St: TryStream, - F: FnMut(&St::Ok) -> Fut, - Fut: TryFuture, +where + St: TryStream, + F: FnMut(&St::Ok) -> Fut, + Fut: TryFuture, { unsafe_unpinned!(f: F); unsafe_pinned!(pending_fut: Option); @@ -53,13 +58,7 @@ impl TrySkipWhile unsafe_unpinned!(done_skipping: bool); pub(super) fn new(stream: St, f: F) -> TrySkipWhile { - TrySkipWhile { - stream, - f, - pending_fut: None, - pending_item: None, - done_skipping: false, - } + TrySkipWhile { stream, f, pending_fut: None, pending_item: None, done_skipping: false } } /// Acquires a reference to the underlying stream that this combinator is @@ -96,16 +95,14 @@ impl TrySkipWhile } impl Stream for TrySkipWhile - where St: TryStream, - F: FnMut(&St::Ok) -> Fut, - Fut: TryFuture, +where + St: TryStream, + F: FnMut(&St::Ok) -> Fut, + Fut: TryFuture, { type Item = Result; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if self.done_skipping { return self.as_mut().stream().try_poll_next(cx); } @@ -127,7 +124,7 @@ impl Stream for TrySkipWhile if !skipped { *self.as_mut().done_skipping() = true; - return Poll::Ready(Some(Ok(item))) + return Poll::Ready(Some(Ok(item))); } } } @@ -144,9 +141,10 @@ impl Stream for TrySkipWhile } impl FusedStream for TrySkipWhile - where St: TryStream + FusedStream, - F: FnMut(&St::Ok) -> Fut, - Fut: TryFuture, +where + St: TryStream + FusedStream, + F: FnMut(&St::Ok) -> Fut, + Fut: TryFuture, { fn is_terminated(&self) -> bool { self.pending_item.is_none() && self.stream.is_terminated() @@ -156,7 +154,8 @@ impl FusedStream for TrySkipWhile // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl Sink for TrySkipWhile - where S: TryStream + Sink, +where + S: TryStream + Sink, { type Error = E; diff --git a/futures-util/src/stream/try_stream/try_unfold.rs b/futures-util/src/stream/try_stream/try_unfold.rs index 6266274cd5..c770ecce6f 100644 --- a/futures-util/src/stream/try_stream/try_unfold.rs +++ b/futures-util/src/stream/try_stream/try_unfold.rs @@ -59,11 +59,7 @@ where F: FnMut(T) -> Fut, Fut: TryFuture>, { - TryUnfold { - f, - state: Some(init), - fut: None, - } + TryUnfold { f, state: Some(init), fut: None } } /// Stream for the [`try_unfold`] function. @@ -82,10 +78,7 @@ where Fut: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("TryUnfold") - .field("state", &self.state) - .field("fut", &self.fut) - .finish() + f.debug_struct("TryUnfold").field("state", &self.state).field("fut", &self.fut).finish() } } diff --git a/futures-util/src/stream/unfold.rs b/futures-util/src/stream/unfold.rs index 3153f83711..5c85d58d2e 100644 --- a/futures-util/src/stream/unfold.rs +++ b/futures-util/src/stream/unfold.rs @@ -45,14 +45,11 @@ use pin_utils::{unsafe_pinned, unsafe_unpinned}; /// # }); /// ``` pub fn unfold(init: T, f: F) -> Unfold - where F: FnMut(T) -> Fut, - Fut: Future>, +where + F: FnMut(T) -> Fut, + Fut: Future>, { - Unfold { - f, - state: Some(init), - fut: None, - } + Unfold { f, state: Some(init), fut: None } } /// Stream for the [`unfold`] function. @@ -71,10 +68,7 @@ where Fut: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Unfold") - .field("state", &self.state) - .field("fut", &self.fut) - .finish() + f.debug_struct("Unfold").field("state", &self.state).field("fut", &self.fut).finish() } } @@ -85,8 +79,9 @@ impl Unfold { } impl FusedStream for Unfold - where F: FnMut(T) -> Fut, - Fut: Future>, +where + F: FnMut(T) -> Fut, + Fut: Future>, { fn is_terminated(&self) -> bool { self.state.is_none() && self.fut.is_none() @@ -94,22 +89,24 @@ impl FusedStream for Unfold } impl Stream for Unfold - where F: FnMut(T) -> Fut, - Fut: Future>, +where + F: FnMut(T) -> Fut, + Fut: Future>, { type Item = Item; - fn poll_next( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if let Some(state) = self.as_mut().state().take() { let fut = (self.as_mut().f())(state); self.as_mut().fut().set(Some(fut)); } - let step = ready!(self.as_mut().fut().as_pin_mut() - .expect("Unfold must not be polled after it returned `Poll::Ready(None)`").poll(cx)); + let step = ready!(self + .as_mut() + .fut() + .as_pin_mut() + .expect("Unfold must not be polled after it returned `Poll::Ready(None)`") + .poll(cx)); self.as_mut().fut().set(None); if let Some((item, next_state)) = step { diff --git a/futures-util/src/task/mod.rs b/futures-util/src/task/mod.rs index fb3b7adacd..ac5aaa886f 100644 --- a/futures-util/src/task/mod.rs +++ b/futures-util/src/task/mod.rs @@ -14,14 +14,11 @@ cfg_target_has_atomic! { } mod spawn; -pub use self::spawn::{SpawnExt, LocalSpawnExt}; +pub use self::spawn::{LocalSpawnExt, SpawnExt}; -pub use futures_core::task::{Context, Poll, Waker, RawWaker, RawWakerVTable}; +pub use futures_core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker}; -pub use futures_task::{ - Spawn, LocalSpawn, SpawnError, - FutureObj, LocalFutureObj, UnsafeFutureObj, -}; +pub use futures_task::{FutureObj, LocalFutureObj, LocalSpawn, Spawn, SpawnError, UnsafeFutureObj}; pub use futures_task::noop_waker; #[cfg(feature = "std")] diff --git a/futures/src/lib.rs b/futures/src/lib.rs index 3cdb3d34ee..a4627a31b4 100644 --- a/futures/src/lib.rs +++ b/futures/src/lib.rs @@ -80,16 +80,12 @@ #![cfg_attr(feature = "cfg-target-has-atomic", feature(cfg_target_has_atomic))] #![cfg_attr(feature = "read-initializer", feature(read_initializer))] - #![cfg_attr(not(feature = "std"), no_std)] - #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms, unreachable_pub)] // It cannot be included in the published code because this lints have false positives in the minimum required version. #![cfg_attr(test, warn(single_use_lifetimes))] #![warn(clippy::all)] - #![doc(test(attr(deny(warnings), allow(dead_code, unused_assignments, unused_variables))))] - #![doc(html_root_url = "https://docs.rs/futures/0.3.0")] #[cfg(all(feature = "cfg-target-has-atomic", not(feature = "unstable")))] @@ -101,19 +97,27 @@ compile_error!("The `bilock` feature requires the `unstable` feature as an expli #[cfg(all(feature = "read-initializer", not(feature = "unstable")))] compile_error!("The `read-initializer` feature requires the `unstable` feature as an explicit opt-in to unstable features"); -#[doc(hidden)] pub use futures_core::future::{Future, TryFuture}; -#[doc(hidden)] pub use futures_util::future::{FutureExt, TryFutureExt}; +#[doc(hidden)] +pub use futures_core::future::{Future, TryFuture}; +#[doc(hidden)] +pub use futures_util::future::{FutureExt, TryFutureExt}; -#[doc(hidden)] pub use futures_core::stream::{Stream, TryStream}; -#[doc(hidden)] pub use futures_util::stream::{StreamExt, TryStreamExt}; +#[doc(hidden)] +pub use futures_core::stream::{Stream, TryStream}; +#[doc(hidden)] +pub use futures_util::stream::{StreamExt, TryStreamExt}; -#[doc(hidden)] pub use futures_sink::Sink; -#[doc(hidden)] pub use futures_util::sink::SinkExt; +#[doc(hidden)] +pub use futures_sink::Sink; +#[doc(hidden)] +pub use futures_util::sink::SinkExt; #[cfg(feature = "std")] -#[doc(hidden)] pub use futures_io::{AsyncRead, AsyncWrite, AsyncSeek, AsyncBufRead}; +#[doc(hidden)] +pub use futures_io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite}; #[cfg(feature = "std")] -#[doc(hidden)] pub use futures_util::{AsyncReadExt, AsyncWriteExt, AsyncSeekExt, AsyncBufReadExt}; +#[doc(hidden)] +pub use futures_util::{AsyncBufReadExt, AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; // Macro reexports pub use futures_core::ready; // Readiness propagation @@ -153,23 +157,12 @@ pub mod compat { //! library is activated. pub use futures_util::compat::{ - Compat, - CompatSink, - Compat01As03, - Compat01As03Sink, - Executor01Future, - Executor01As03, - Executor01CompatExt, - Future01CompatExt, - Stream01CompatExt, - Sink01CompatExt, + Compat, Compat01As03, Compat01As03Sink, CompatSink, Executor01As03, Executor01CompatExt, + Executor01Future, Future01CompatExt, Sink01CompatExt, Stream01CompatExt, }; #[cfg(feature = "io-compat")] - pub use futures_util::compat::{ - AsyncRead01CompatExt, - AsyncWrite01CompatExt, - }; + pub use futures_util::compat::{AsyncRead01CompatExt, AsyncWrite01CompatExt}; } #[cfg(feature = "executor")] @@ -216,10 +209,8 @@ pub mod executor { //! completion on the current thread. pub use futures_executor::{ - BlockingStream, - Enter, EnterError, - LocalSpawner, LocalPool, - block_on, block_on_stream, enter, + block_on, block_on_stream, enter, BlockingStream, Enter, EnterError, LocalPool, + LocalSpawner, }; #[cfg(feature = "thread-pool")] @@ -239,9 +230,7 @@ pub mod future { //! [`ready`](crate::future::ready), which constructs a future with an //! immediate defined value. - pub use futures_core::future::{ - Future, TryFuture, FusedFuture, - }; + pub use futures_core::future::{FusedFuture, Future, TryFuture}; #[cfg(feature = "alloc")] pub use futures_core::future::{BoxFuture, LocalBoxFuture}; @@ -249,48 +238,25 @@ pub mod future { pub use futures_task::{FutureObj, LocalFutureObj, UnsafeFutureObj}; pub use futures_util::future::{ - lazy, Lazy, - maybe_done, MaybeDone, - pending, Pending, - poll_fn, PollFn, - ready, ok, err, Ready, - join, join3, join4, join5, - Join, Join3, Join4, Join5, - select, Select, - try_join, try_join3, try_join4, try_join5, - TryJoin, TryJoin3, TryJoin4, TryJoin5, - try_select, TrySelect, - Either, - OptionFuture, - - FutureExt, - FlattenStream, Flatten, Fuse, Inspect, IntoStream, Map, Then, UnitError, - NeverError, - - TryFutureExt, - AndThen, ErrInto, FlattenSink, IntoFuture, MapErr, MapOk, OrElse, - InspectOk, InspectErr, TryFlattenStream, UnwrapOrElse, + err, join, join3, join4, join5, lazy, maybe_done, ok, pending, poll_fn, ready, select, + try_join, try_join3, try_join4, try_join5, try_select, AndThen, Either, ErrInto, Flatten, + FlattenSink, FlattenStream, Fuse, FutureExt, Inspect, InspectErr, InspectOk, IntoFuture, + IntoStream, Join, Join3, Join4, Join5, Lazy, Map, MapErr, MapOk, MaybeDone, NeverError, + OptionFuture, OrElse, Pending, PollFn, Ready, Select, Then, TryFlattenStream, TryFutureExt, + TryJoin, TryJoin3, TryJoin4, TryJoin5, TrySelect, UnitError, UnwrapOrElse, }; #[cfg(feature = "alloc")] pub use futures_util::future::{ - join_all, JoinAll, - select_all, SelectAll, - try_join_all, TryJoinAll, - select_ok, SelectOk, + join_all, select_all, select_ok, try_join_all, JoinAll, SelectAll, SelectOk, TryJoinAll, }; #[cfg_attr(feature = "cfg-target-has-atomic", cfg(target_has_atomic = "ptr"))] #[cfg(feature = "alloc")] - pub use futures_util::future::{ - abortable, Abortable, AbortHandle, AbortRegistration, Aborted, - }; + pub use futures_util::future::{abortable, AbortHandle, AbortRegistration, Abortable, Aborted}; #[cfg(feature = "std")] - pub use futures_util::future::{ - Remote, RemoteHandle, - CatchUnwind, Shared, - }; + pub use futures_util::future::{CatchUnwind, Remote, RemoteHandle, Shared}; } #[cfg(feature = "std")] @@ -320,20 +286,19 @@ pub mod io { //! library is activated, and it is activated by default. pub use futures_io::{ - AsyncRead, AsyncWrite, AsyncSeek, AsyncBufRead, Error, ErrorKind, - IoSlice, IoSliceMut, Result, SeekFrom, + AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, Error, ErrorKind, IoSlice, IoSliceMut, + Result, SeekFrom, }; #[cfg(feature = "read-initializer")] pub use futures_io::Initializer; pub use futures_util::io::{ - AsyncReadExt, AsyncWriteExt, AsyncSeekExt, AsyncBufReadExt, AllowStdIo, - BufReader, BufWriter, Cursor, Chain, Close, copy, Copy, copy_buf, CopyBuf, - empty, Empty, Flush, IntoSink, Lines, Read, ReadExact, ReadHalf, - ReadLine, ReadToEnd, ReadToString, ReadUntil, ReadVectored, repeat, - Repeat, Seek, sink, Sink, Take, Window, Write, WriteAll, WriteHalf, - WriteVectored, + copy, copy_buf, empty, repeat, sink, AllowStdIo, AsyncBufReadExt, AsyncReadExt, + AsyncSeekExt, AsyncWriteExt, BufReader, BufWriter, Chain, Close, Copy, CopyBuf, Cursor, + Empty, Flush, IntoSink, Lines, Read, ReadExact, ReadHalf, ReadLine, ReadToEnd, + ReadToString, ReadUntil, ReadVectored, Repeat, Seek, Sink, Take, Window, Write, WriteAll, + WriteHalf, WriteVectored, }; } @@ -349,7 +314,7 @@ pub mod lock { pub use futures_util::lock::{BiLock, BiLockAcquire, BiLockGuard, ReuniteError}; #[cfg(feature = "std")] - pub use futures_util::lock::{MappedMutexGuard, Mutex, MutexLockFuture, MutexGuard}; + pub use futures_util::lock::{MappedMutexGuard, Mutex, MutexGuard, MutexLockFuture}; } pub mod prelude { @@ -367,25 +332,23 @@ pub mod prelude { //! The prelude may grow over time as additional items see ubiquitous use. pub use crate::future::{self, Future, TryFuture}; - pub use crate::stream::{self, Stream, TryStream}; pub use crate::sink::{self, Sink}; + pub use crate::stream::{self, Stream, TryStream}; #[doc(no_inline)] pub use crate::future::{FutureExt as _, TryFutureExt as _}; #[doc(no_inline)] - pub use crate::stream::{StreamExt as _, TryStreamExt as _}; - #[doc(no_inline)] pub use crate::sink::SinkExt as _; + #[doc(no_inline)] + pub use crate::stream::{StreamExt as _, TryStreamExt as _}; #[cfg(feature = "std")] - pub use crate::io::{ - AsyncRead, AsyncWrite, AsyncSeek, AsyncBufRead, - }; + pub use crate::io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite}; #[cfg(feature = "std")] #[doc(no_inline)] pub use crate::io::{ - AsyncReadExt as _, AsyncWriteExt as _, AsyncSeekExt as _, AsyncBufReadExt as _, + AsyncBufReadExt as _, AsyncReadExt as _, AsyncSeekExt as _, AsyncWriteExt as _, }; } @@ -402,8 +365,7 @@ pub mod sink { pub use futures_sink::Sink; pub use futures_util::sink::{ - Close, Flush, Send, SendAll, SinkErrInto, SinkMapErr, With, - SinkExt, Fanout, Drain, drain, + drain, Close, Drain, Fanout, Flush, Send, SendAll, SinkErrInto, SinkExt, SinkMapErr, With, WithFlatMap, }; @@ -423,68 +385,52 @@ pub mod stream { //! - Top-level stream contructors like [`iter`](crate::stream::iter) //! which creates a stream from an iterator. - pub use futures_core::stream::{ - Stream, TryStream, FusedStream, - }; + pub use futures_core::stream::{FusedStream, Stream, TryStream}; #[cfg(feature = "alloc")] pub use futures_core::stream::{BoxStream, LocalBoxStream}; pub use futures_util::stream::{ - iter, Iter, - repeat, Repeat, - empty, Empty, - pending, Pending, - once, Once, - poll_fn, PollFn, - select, Select, - unfold, Unfold, - try_unfold, TryUnfold, - - StreamExt, - Chain, Collect, Concat, Enumerate, Filter, FilterMap, Flatten, Fold, - Forward, ForEach, Fuse, StreamFuture, Inspect, Map, Next, - SelectNextSome, Peek, Peekable, Scan, Skip, SkipWhile, Take, TakeWhile, - Then, Zip, - - TryStreamExt, - AndThen, ErrInto, MapOk, MapErr, OrElse, - InspectOk, InspectErr, - TryNext, TryForEach, TryFilter, TryFilterMap, TryFlatten, - TryCollect, TryConcat, TryFold, TrySkipWhile, - IntoStream, + empty, iter, once, pending, poll_fn, repeat, select, try_unfold, unfold, AndThen, Chain, + Collect, Concat, Empty, Enumerate, ErrInto, Filter, FilterMap, Flatten, Fold, ForEach, + Forward, Fuse, Inspect, InspectErr, InspectOk, IntoStream, Iter, Map, MapErr, MapOk, Next, + Once, OrElse, Peek, Peekable, Pending, PollFn, Repeat, Scan, Select, SelectNextSome, Skip, + SkipWhile, StreamExt, StreamFuture, Take, TakeWhile, Then, TryCollect, TryConcat, + TryFilter, TryFilterMap, TryFlatten, TryFold, TryForEach, TryNext, TrySkipWhile, + TryStreamExt, TryUnfold, Unfold, Zip, }; #[cfg(feature = "alloc")] - pub use futures_util::stream::{ - // For StreamExt: - Chunks, - }; + pub use futures_util::stream::Chunks; #[cfg_attr(feature = "cfg-target-has-atomic", cfg(target_has_atomic = "ptr"))] #[cfg(feature = "alloc")] pub use futures_util::stream::{ + futures_unordered, + select_all, + // For StreamExt: + BufferUnordered, + Buffered, + ForEachConcurrent, FuturesOrdered, - futures_unordered, FuturesUnordered, + FuturesUnordered, - // For StreamExt: - BufferUnordered, Buffered, ForEachConcurrent, SplitStream, SplitSink, ReuniteError, - select_all, SelectAll, + SelectAll, + SplitSink, + SplitStream, }; #[cfg(feature = "std")] - pub use futures_util::stream::{ - // For StreamExt: - CatchUnwind, - }; + pub use futures_util::stream::CatchUnwind; #[cfg_attr(feature = "cfg-target-has-atomic", cfg(target_has_atomic = "ptr"))] #[cfg(feature = "alloc")] pub use futures_util::stream::{ // For TryStreamExt: - TryBufferUnordered, TryForEachConcurrent, + TryBufferUnordered, + TryForEachConcurrent, }; #[cfg(feature = "std")] @@ -504,11 +450,10 @@ pub mod task { //! The remaining types and traits in the module are used for implementing //! executors or dealing with synchronization issues around task wakeup. - pub use futures_core::task::{Context, Poll, Waker, RawWaker, RawWakerVTable}; + pub use futures_core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker}; pub use futures_task::{ - Spawn, LocalSpawn, SpawnError, - FutureObj, LocalFutureObj, UnsafeFutureObj, + FutureObj, LocalFutureObj, LocalSpawn, Spawn, SpawnError, UnsafeFutureObj, }; pub use futures_util::task::noop_waker; @@ -517,11 +462,11 @@ pub mod task { pub use futures_util::task::noop_waker_ref; #[cfg(feature = "alloc")] - pub use futures_util::task::{SpawnExt, LocalSpawnExt}; + pub use futures_util::task::{LocalSpawnExt, SpawnExt}; #[cfg_attr(feature = "cfg-target-has-atomic", cfg(target_has_atomic = "ptr"))] #[cfg(feature = "alloc")] - pub use futures_util::task::{waker, waker_ref, WakerRef, ArcWake}; + pub use futures_util::task::{waker, waker_ref, ArcWake, WakerRef}; #[cfg_attr(feature = "cfg-target-has-atomic", cfg(target_has_atomic = "ptr"))] pub use futures_util::task::AtomicWaker; @@ -551,10 +496,10 @@ pub use futures_util::async_await; #[doc(hidden)] pub mod inner_macro { pub use futures_util::join; - pub use futures_util::try_join; #[cfg(feature = "std")] pub use futures_util::select; pub use futures_util::select_biased; + pub use futures_util::try_join; } #[cfg(feature = "async-await")] diff --git a/futures/tests/arc_wake.rs b/futures/tests/arc_wake.rs index 1940e4f98b..234acfe639 100644 --- a/futures/tests/arc_wake.rs +++ b/futures/tests/arc_wake.rs @@ -7,9 +7,7 @@ struct CountingWaker { impl CountingWaker { fn new() -> CountingWaker { - CountingWaker { - nr_wake: Mutex::new(0), - } + CountingWaker { nr_wake: Mutex::new(0) } } fn wakes(&self) -> i32 { @@ -58,7 +56,10 @@ fn proper_refcount_on_wake_panic() { let some_w = Arc::new(PanicWaker); let w1: Waker = task::waker(some_w.clone()); - assert_eq!("WAKE UP", *std::panic::catch_unwind(|| w1.wake_by_ref()).unwrap_err().downcast::<&str>().unwrap()); + assert_eq!( + "WAKE UP", + *std::panic::catch_unwind(|| w1.wake_by_ref()).unwrap_err().downcast::<&str>().unwrap() + ); assert_eq!(2, Arc::strong_count(&some_w)); // some_w + w1 drop(w1); assert_eq!(1, Arc::strong_count(&some_w)); // some_w diff --git a/futures/tests/async_await_macros.rs b/futures/tests/async_await_macros.rs index bc717df535..cce7f6e619 100644 --- a/futures/tests/async_await_macros.rs +++ b/futures/tests/async_await_macros.rs @@ -1,12 +1,12 @@ -#![recursion_limit="128"] +#![recursion_limit = "128"] -use futures::{pending, pin_mut, poll, join, try_join, select}; use futures::channel::{mpsc, oneshot}; use futures::executor::block_on; -use futures::future::{self, FutureExt, poll_fn}; +use futures::future::{self, poll_fn, FutureExt}; use futures::sink::SinkExt; use futures::stream::StreamExt; use futures::task::{Context, Poll}; +use futures::{join, pending, pin_mut, poll, select, try_join}; #[test] fn poll_and_pending() { @@ -185,9 +185,7 @@ fn select_size() { #[test] fn select_on_non_unpin_expressions() { // The returned Future is !Unpin - let make_non_unpin_fut = || { async { - 5 - }}; + let make_non_unpin_fut = || async { 5 }; let res = block_on(async { let select_res; @@ -203,9 +201,7 @@ fn select_on_non_unpin_expressions() { #[test] fn select_on_non_unpin_expressions_with_default() { // The returned Future is !Unpin - let make_non_unpin_fut = || { async { - 5 - }}; + let make_non_unpin_fut = || async { 5 }; let res = block_on(async { let select_res; @@ -222,9 +218,7 @@ fn select_on_non_unpin_expressions_with_default() { #[test] fn select_on_non_unpin_size() { // The returned Future is !Unpin - let make_non_unpin_fut = || { async { - 5 - }}; + let make_non_unpin_fut = || async { 5 }; let fut = async { let select_res; @@ -344,17 +338,10 @@ fn try_join_size() { #[test] fn join_doesnt_require_unpin() { - let _ = async { - join!(async {}, async {}) - }; + let _ = async { join!(async {}, async {}) }; } #[test] fn try_join_doesnt_require_unpin() { - let _ = async { - try_join!( - async { Ok::<(), ()>(()) }, - async { Ok::<(), ()>(()) }, - ) - }; + let _ = async { try_join!(async { Ok::<(), ()>(()) }, async { Ok::<(), ()>(()) },) }; } diff --git a/futures/tests/basic_combinators.rs b/futures/tests/basic_combinators.rs index fa65b6f5f1..372ab48b79 100644 --- a/futures/tests/basic_combinators.rs +++ b/futures/tests/basic_combinators.rs @@ -13,17 +13,21 @@ fn basic_future_combinators() { tx1.send(x).unwrap(); // Send 1 tx1.send(2).unwrap(); // Send 2 future::ready(3) - }).map(move |x| { + }) + .map(move |x| { tx2.send(x).unwrap(); // Send 3 tx2.send(4).unwrap(); // Send 4 5 - }).map(move |x| { + }) + .map(move |x| { tx3.send(x).unwrap(); // Send 5 }); assert!(rx.try_recv().is_err()); // Not started yet fut.run_in_background(); // Start it - for i in 1..=5 { assert_eq!(rx.recv(), Ok(i)); } // Check it + for i in 1..=5 { + assert_eq!(rx.recv(), Ok(i)); + } // Check it assert!(rx.recv().is_err()); // Should be done } @@ -93,6 +97,8 @@ fn basic_try_future_combinators() { assert!(rx.try_recv().is_err()); // Not started yet fut.run_in_background(); // Start it - for i in 1..=12 { assert_eq!(rx.recv(), Ok(i)); } // Check it + for i in 1..=12 { + assert_eq!(rx.recv(), Ok(i)); + } // Check it assert!(rx.recv().is_err()); // Should be done } diff --git a/futures/tests/buffer_unordered.rs b/futures/tests/buffer_unordered.rs index 1c559c8544..9a2ee174ed 100644 --- a/futures/tests/buffer_unordered.rs +++ b/futures/tests/buffer_unordered.rs @@ -1,4 +1,4 @@ -use futures::channel::{oneshot, mpsc}; +use futures::channel::{mpsc, oneshot}; use futures::executor::{block_on, block_on_stream}; use futures::sink::SinkExt; use futures::stream::StreamExt; diff --git a/futures/tests/compat.rs b/futures/tests/compat.rs index 39adc7cba4..c4125d895b 100644 --- a/futures/tests/compat.rs +++ b/futures/tests/compat.rs @@ -1,16 +1,14 @@ #![cfg(feature = "compat")] -use tokio::timer::Delay; -use tokio::runtime::Runtime; -use std::time::Instant; -use futures::prelude::*; use futures::compat::Future01CompatExt; +use futures::prelude::*; +use std::time::Instant; +use tokio::runtime::Runtime; +use tokio::timer::Delay; #[test] fn can_use_01_futures_in_a_03_future_running_on_a_01_executor() { - let f = async { - Delay::new(Instant::now()).compat().await - }; + let f = async { Delay::new(Instant::now()).compat().await }; let mut runtime = Runtime::new().unwrap(); runtime.block_on(f.boxed().compat()).unwrap(); diff --git a/futures/tests/eager_drop.rs b/futures/tests/eager_drop.rs index 674e40121d..4e89891a5f 100644 --- a/futures/tests/eager_drop.rs +++ b/futures/tests/eager_drop.rs @@ -14,7 +14,10 @@ fn map_ok() { let (tx2, rx2) = mpsc::channel::<()>(); future::ready::>(Err(1)) - .map_ok(move |_| { let _tx1 = tx1; panic!("should not run"); }) + .map_ok(move |_| { + let _tx1 = tx1; + panic!("should not run"); + }) .map(move |_| { assert!(rx1.recv().is_err()); tx2.send(()).unwrap() @@ -32,7 +35,10 @@ fn map_err() { let (tx2, rx2) = mpsc::channel::<()>(); future::ready::>(Ok(1)) - .map_err(move |_| { let _tx1 = tx1; panic!("should not run"); }) + .map_err(move |_| { + let _tx1 = tx1; + panic!("should not run"); + }) .map(move |_| { assert!(rx1.recv().is_err()); tx2.send(()).unwrap() @@ -65,7 +71,7 @@ fn then_drops_eagerly() { let (tx1, rx1) = mpsc::channel::<()>(); let (tx2, rx2) = mpsc::channel::<()>(); - FutureData { _data: tx1, future: rx0.unwrap_or_else(|_| { panic!() }) } + FutureData { _data: tx1, future: rx0.unwrap_or_else(|_| panic!()) } .then(move |_| { assert!(rx1.recv().is_err()); // tx1 should have been dropped tx2.send(()).unwrap(); @@ -84,7 +90,7 @@ fn and_then_drops_eagerly() { let (tx1, rx1) = mpsc::channel::<()>(); let (tx2, rx2) = mpsc::channel::<()>(); - FutureData { _data: tx1, future: rx0.unwrap_or_else(|_| { panic!() }) } + FutureData { _data: tx1, future: rx0.unwrap_or_else(|_| panic!()) } .and_then(move |_| { assert!(rx1.recv().is_err()); // tx1 should have been dropped tx2.send(()).unwrap(); @@ -103,7 +109,7 @@ fn or_else_drops_eagerly() { let (tx1, rx1) = mpsc::channel::<()>(); let (tx2, rx2) = mpsc::channel::<()>(); - FutureData { _data: tx1, future: rx0.unwrap_or_else(|_| { panic!() }) } + FutureData { _data: tx1, future: rx0.unwrap_or_else(|_| panic!()) } .or_else(move |_| { assert!(rx1.recv().is_err()); // tx1 should have been dropped tx2.send(()).unwrap(); diff --git a/futures/tests/future_obj.rs b/futures/tests/future_obj.rs index c6b18fc85c..0e5253464e 100644 --- a/futures/tests/future_obj.rs +++ b/futures/tests/future_obj.rs @@ -1,6 +1,6 @@ -use futures::future::{Future, FutureObj, FutureExt}; -use std::pin::Pin; +use futures::future::{Future, FutureExt, FutureObj}; use futures::task::{Context, Poll}; +use std::pin::Pin; #[test] fn dropping_does_not_segfault() { diff --git a/futures/tests/future_try_flatten_stream.rs b/futures/tests/future_try_flatten_stream.rs index 082c5efa9a..99179759a0 100644 --- a/futures/tests/future_try_flatten_stream.rs +++ b/futures/tests/future_try_flatten_stream.rs @@ -1,7 +1,7 @@ use core::marker::PhantomData; use core::pin::Pin; use futures::executor::block_on_stream; -use futures::future::{ok, err, TryFutureExt}; +use futures::future::{err, ok, TryFutureExt}; use futures::sink::Sink; use futures::stream::{self, Stream, StreamExt}; use futures::task::{Context, Poll}; @@ -20,7 +20,7 @@ fn successful_future() { } struct PanickingStream { - _marker: PhantomData<(T, E)> + _marker: PhantomData<(T, E)>, } impl Stream for PanickingStream { diff --git a/futures/tests/futures_ordered.rs b/futures/tests/futures_ordered.rs index d06b62f76c..7506c65a63 100644 --- a/futures/tests/futures_ordered.rs +++ b/futures/tests/futures_ordered.rs @@ -1,7 +1,7 @@ use futures::channel::oneshot; use futures::executor::{block_on, block_on_stream}; use futures::future::{self, join, Future, FutureExt, TryFutureExt}; -use futures::stream::{StreamExt, FuturesOrdered}; +use futures::stream::{FuturesOrdered, StreamExt}; use futures_test::task::noop_context; use std::any::Any; @@ -32,10 +32,9 @@ fn works_2() { let (b_tx, b_rx) = oneshot::channel::(); let (c_tx, c_rx) = oneshot::channel::(); - let mut stream = vec![ - a_rx.boxed(), - join(b_rx, c_rx).map(|(a, b)| Ok(a? + b?)).boxed(), - ].into_iter().collect::>(); + let mut stream = vec![a_rx.boxed(), join(b_rx, c_rx).map(|(a, b)| Ok(a? + b?)).boxed()] + .into_iter() + .collect::>(); let mut cx = noop_context(); a_tx.send(33).unwrap(); @@ -48,13 +47,11 @@ fn works_2() { #[test] fn from_iterator() { - let stream = vec![ - future::ready::(1), - future::ready::(2), - future::ready::(3) - ].into_iter().collect::>(); + let stream = vec![future::ready::(1), future::ready::(2), future::ready::(3)] + .into_iter() + .collect::>(); assert_eq!(stream.len(), 3); - assert_eq!(block_on(stream.collect::>()), vec![1,2,3]); + assert_eq!(block_on(stream.collect::>()), vec![1, 2, 3]); } #[test] @@ -65,10 +62,14 @@ fn queue_never_unblocked() { let mut stream = vec![ Box::new(a_rx) as Box + Unpin>, - Box::new(future::try_select(b_rx, c_rx) - .map_err(|e| e.factor_first().0) - .and_then(|e| future::ok(Box::new(e) as Box))) as _, - ].into_iter().collect::>(); + Box::new( + future::try_select(b_rx, c_rx) + .map_err(|e| e.factor_first().0) + .and_then(|e| future::ok(Box::new(e) as Box)), + ) as _, + ] + .into_iter() + .collect::>(); let cx = &mut noop_context(); for _ in 0..10 { diff --git a/futures/tests/futures_unordered.rs b/futures/tests/futures_unordered.rs index 57eb98fd1b..d51f6f7bbf 100644 --- a/futures/tests/futures_unordered.rs +++ b/futures/tests/futures_unordered.rs @@ -44,11 +44,8 @@ fn works_1() { let (b_tx, b_rx) = oneshot::channel::(); let (c_tx, c_rx) = oneshot::channel::(); - let mut iter = block_on_stream( - vec![a_rx, b_rx, c_rx] - .into_iter() - .collect::>(), - ); + let mut iter = + block_on_stream(vec![a_rx, b_rx, c_rx].into_iter().collect::>()); b_tx.send(99).unwrap(); assert_eq!(Some(Ok(99)), iter.next()); @@ -66,12 +63,9 @@ fn works_2() { let (b_tx, b_rx) = oneshot::channel::(); let (c_tx, c_rx) = oneshot::channel::(); - let mut stream = vec![ - a_rx.boxed(), - join(b_rx, c_rx).map(|(a, b)| Ok(a? + b?)).boxed(), - ] - .into_iter() - .collect::>(); + let mut stream = vec![a_rx.boxed(), join(b_rx, c_rx).map(|(a, b)| Ok(a? + b?)).boxed()] + .into_iter() + .collect::>(); a_tx.send(9).unwrap(); b_tx.send(10).unwrap(); @@ -85,13 +79,9 @@ fn works_2() { #[test] fn from_iterator() { - let stream = vec![ - future::ready::(1), - future::ready::(2), - future::ready::(3), - ] - .into_iter() - .collect::>(); + let stream = vec![future::ready::(1), future::ready::(2), future::ready::(3)] + .into_iter() + .collect::>(); assert_eq!(stream.len(), 3); assert_eq!(block_on(stream.collect::>()), vec![1, 2, 3]); } @@ -127,9 +117,7 @@ fn iter_mut_cancel() { let (b_tx, b_rx) = oneshot::channel::(); let (c_tx, c_rx) = oneshot::channel::(); - let mut stream = vec![a_rx, b_rx, c_rx] - .into_iter() - .collect::>(); + let mut stream = vec![a_rx, b_rx, c_rx].into_iter().collect::>(); for rx in stream.iter_mut() { rx.close(); @@ -149,13 +137,10 @@ fn iter_mut_cancel() { #[test] fn iter_mut_len() { - let mut stream = vec![ - future::pending::<()>(), - future::pending::<()>(), - future::pending::<()>(), - ] - .into_iter() - .collect::>(); + let mut stream = + vec![future::pending::<()>(), future::pending::<()>(), future::pending::<()>()] + .into_iter() + .collect::>(); let mut iter_mut = stream.iter_mut(); assert_eq!(iter_mut.len(), 3); @@ -215,13 +200,9 @@ fn iter_cancel() { #[test] fn iter_len() { - let stream = vec![ - future::pending::<()>(), - future::pending::<()>(), - future::pending::<()>(), - ] - .into_iter() - .collect::>(); + let stream = vec![future::pending::<()>(), future::pending::<()>(), future::pending::<()>()] + .into_iter() + .collect::>(); let mut iter = stream.iter(); assert_eq!(iter.len(), 3); diff --git a/futures/tests/inspect.rs b/futures/tests/inspect.rs index 42f6f73634..eacd1f78a2 100644 --- a/futures/tests/inspect.rs +++ b/futures/tests/inspect.rs @@ -6,7 +6,9 @@ fn smoke() { let mut counter = 0; { - let work = future::ready::(40).inspect(|val| { counter += *val; }); + let work = future::ready::(40).inspect(|val| { + counter += *val; + }); assert_eq!(block_on(work), 40); } diff --git a/futures/tests/io_buf_reader.rs b/futures/tests/io_buf_reader.rs index a3d723a691..73375443fe 100644 --- a/futures/tests/io_buf_reader.rs +++ b/futures/tests/io_buf_reader.rs @@ -1,8 +1,8 @@ use futures::executor::block_on; use futures::future::{Future, FutureExt}; use futures::io::{ - AsyncSeek, AsyncSeekExt, AsyncBufRead, AsyncBufReadExt, AsyncRead, AsyncReadExt, - AllowStdIo, BufReader, Cursor, SeekFrom, + AllowStdIo, AsyncBufRead, AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncSeek, AsyncSeekExt, + BufReader, Cursor, SeekFrom, }; use futures::task::{Context, Poll}; use futures_test::task::noop_context; @@ -92,7 +92,7 @@ fn test_buffered_reader_seek() { fn test_buffered_reader_seek_underflow() { // gimmick reader that yields its position modulo 256 for each byte struct PositionReader { - pos: u64 + pos: u64, } impl io::Read for PositionReader { fn read(&mut self, buf: &mut [u8]) -> io::Result { @@ -123,7 +123,7 @@ fn test_buffered_reader_seek_underflow() { let mut reader = BufReader::with_capacity(5, AllowStdIo::new(PositionReader { pos: 0 })); assert_eq!(run_fill_buf!(reader).ok(), Some(&[0, 1, 2, 3, 4][..])); - assert_eq!(block_on(reader.seek(SeekFrom::End(-5))).ok(), Some(u64::max_value()-5)); + assert_eq!(block_on(reader.seek(SeekFrom::End(-5))).ok(), Some(u64::max_value() - 5)); assert_eq!(run_fill_buf!(reader).ok().map(|s| s.len()), Some(5)); // the following seek will require two underlying seeks let expected = 9_223_372_036_854_775_802; @@ -161,9 +161,11 @@ impl<'a> MaybePending<'a> { } impl AsyncRead for MaybePending<'_> { - fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) - -> Poll> - { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut [u8], + ) -> Poll> { if self.ready_read { self.ready_read = false; Pin::new(&mut self.inner).poll_read(cx, buf) @@ -175,12 +177,12 @@ impl AsyncRead for MaybePending<'_> { } impl AsyncBufRead for MaybePending<'_> { - fn poll_fill_buf(mut self: Pin<&mut Self>, _: &mut Context<'_>) - -> Poll> - { + fn poll_fill_buf(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { if self.ready_fill_buf { self.ready_fill_buf = false; - if self.inner.is_empty() { return Poll::Ready(Ok(&[])) } + if self.inner.is_empty() { + return Poll::Ready(Ok(&[])); + } let len = cmp::min(2, self.inner.len()); Poll::Ready(Ok(&self.inner[0..len])) } else { @@ -270,17 +272,17 @@ impl<'a> MaybePendingSeek<'a> { } impl AsyncRead for MaybePendingSeek<'_> { - fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) - -> Poll> - { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut [u8], + ) -> Poll> { Pin::new(&mut self.inner).poll_read(cx, buf) } } impl AsyncBufRead for MaybePendingSeek<'_> { - fn poll_fill_buf(mut self: Pin<&mut Self>, cx: &mut Context<'_>) - -> Poll> - { + fn poll_fill_buf(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this: *mut Self = &mut *self as *mut _; Pin::new(&mut unsafe { &mut *this }.inner).poll_fill_buf(cx) } @@ -291,9 +293,11 @@ impl AsyncBufRead for MaybePendingSeek<'_> { } impl AsyncSeek for MaybePendingSeek<'_> { - fn poll_seek(mut self: Pin<&mut Self>, cx: &mut Context<'_>, pos: SeekFrom) - -> Poll> - { + fn poll_seek( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + pos: SeekFrom, + ) -> Poll> { if self.ready { self.ready = false; Pin::new(&mut self.inner).poll_seek(cx, pos) diff --git a/futures/tests/io_buf_writer.rs b/futures/tests/io_buf_writer.rs index 7bdcd16df0..c50d4a7c48 100644 --- a/futures/tests/io_buf_writer.rs +++ b/futures/tests/io_buf_writer.rs @@ -1,6 +1,8 @@ use futures::executor::block_on; use futures::future::{Future, FutureExt}; -use futures::io::{AsyncSeek, AsyncSeekExt, AsyncWrite, AsyncWriteExt, BufWriter, Cursor, SeekFrom}; +use futures::io::{ + AsyncSeek, AsyncSeekExt, AsyncWrite, AsyncWriteExt, BufWriter, Cursor, SeekFrom, +}; use futures::task::{Context, Poll}; use futures_test::task::noop_context; use std::io; @@ -169,7 +171,6 @@ fn maybe_pending_buf_writer_inner_flushes() { assert_eq!(w, [0, 1]); } - struct MaybePendingSeek { inner: Cursor>, ready_write: bool, @@ -207,9 +208,11 @@ impl AsyncWrite for MaybePendingSeek { } impl AsyncSeek for MaybePendingSeek { - fn poll_seek(mut self: Pin<&mut Self>, cx: &mut Context<'_>, pos: SeekFrom) - -> Poll> - { + fn poll_seek( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + pos: SeekFrom, + ) -> Poll> { if self.ready_seek { self.ready_seek = false; Pin::new(&mut self.inner).poll_seek(cx, pos) diff --git a/futures/tests/io_lines.rs b/futures/tests/io_lines.rs index 39eafa9a66..8ac18c88a6 100644 --- a/futures/tests/io_lines.rs +++ b/futures/tests/io_lines.rs @@ -1,7 +1,7 @@ use futures::executor::block_on; use futures::future::{Future, FutureExt}; -use futures::stream::{self, StreamExt, TryStreamExt}; use futures::io::{AsyncBufReadExt, Cursor}; +use futures::stream::{self, StreamExt, TryStreamExt}; use futures::task::Poll; use futures_test::io::AsyncReadTestExt; use futures_test::task::noop_context; @@ -43,10 +43,8 @@ macro_rules! run_next { #[test] fn maybe_pending() { - let buf = stream::iter(vec![&b"12"[..], &b"\r"[..]]) - .map(Ok) - .into_async_read() - .interleave_pending(); + let buf = + stream::iter(vec![&b"12"[..], &b"\r"[..]]).map(Ok).into_async_read().interleave_pending(); let mut s = buf.lines(); assert_eq!(run_next!(s), "12\r".to_string()); assert!(run(s.next()).is_none()); diff --git a/futures/tests/io_read.rs b/futures/tests/io_read.rs index f99c4edbb6..76c5964e90 100644 --- a/futures/tests/io_read.rs +++ b/futures/tests/io_read.rs @@ -18,7 +18,7 @@ impl AsyncRead for MockReader { fn poll_read( self: Pin<&mut Self>, _cx: &mut Context<'_>, - buf: &mut [u8] + buf: &mut [u8], ) -> Poll> { (self.get_mut().fun)(buf) } @@ -52,7 +52,7 @@ fn read_vectored_first_non_empty() { let cx = &mut panic_context(); let mut buf = [0; 4]; let bufs = &mut [ - io::IoSliceMut::new(&mut []), + io::IoSliceMut::new(&mut []), io::IoSliceMut::new(&mut []), io::IoSliceMut::new(&mut buf), ]; @@ -62,4 +62,3 @@ fn read_vectored_first_non_empty() { assert_eq!(res, Poll::Ready(Ok(4))); assert_eq!(buf, b"four"[..]); } - diff --git a/futures/tests/io_read_exact.rs b/futures/tests/io_read_exact.rs index 4941773cb5..6582e50b80 100644 --- a/futures/tests/io_read_exact.rs +++ b/futures/tests/io_read_exact.rs @@ -8,7 +8,7 @@ fn read_exact() { let res = block_on(reader.read_exact(&mut out)); // read 3 bytes out assert!(res.is_ok()); - assert_eq!(out, [1,2,3]); + assert_eq!(out, [1, 2, 3]); assert_eq!(reader.len(), 2); let res = block_on(reader.read_exact(&mut out)); // read another 3 bytes, but only 2 bytes left diff --git a/futures/tests/io_read_line.rs b/futures/tests/io_read_line.rs index d1dba5e6d2..9676df1e14 100644 --- a/futures/tests/io_read_line.rs +++ b/futures/tests/io_read_line.rs @@ -1,7 +1,7 @@ use futures::executor::block_on; use futures::future::{Future, FutureExt}; -use futures::stream::{self, StreamExt, TryStreamExt}; use futures::io::{AsyncBufReadExt, Cursor}; +use futures::stream::{self, StreamExt, TryStreamExt}; use futures::task::Poll; use futures_test::io::AsyncReadTestExt; use futures_test::task::noop_context; @@ -41,10 +41,8 @@ fn maybe_pending() { assert_eq!(run(buf.read_line(&mut v)).unwrap(), 2); assert_eq!(v, "12"); - let mut buf = stream::iter(vec![&b"12"[..], &b"\n\n"[..]]) - .map(Ok) - .into_async_read() - .interleave_pending(); + let mut buf = + stream::iter(vec![&b"12"[..], &b"\n\n"[..]]).map(Ok).into_async_read().interleave_pending(); let mut v = String::new(); assert_eq!(run(buf.read_line(&mut v)).unwrap(), 3); assert_eq!(v, "12\n"); diff --git a/futures/tests/io_read_to_string.rs b/futures/tests/io_read_to_string.rs index db825af21c..32f0aefb1e 100644 --- a/futures/tests/io_read_to_string.rs +++ b/futures/tests/io_read_to_string.rs @@ -1,7 +1,7 @@ use futures::executor::block_on; use futures::future::{Future, FutureExt}; -use futures::stream::{self, StreamExt, TryStreamExt}; use futures::io::{AsyncReadExt, Cursor}; +use futures::stream::{self, StreamExt, TryStreamExt}; use futures::task::Poll; use futures_test::io::AsyncReadTestExt; use futures_test::task::noop_context; diff --git a/futures/tests/io_read_until.rs b/futures/tests/io_read_until.rs index 5152281795..1d281abadf 100644 --- a/futures/tests/io_read_until.rs +++ b/futures/tests/io_read_until.rs @@ -1,7 +1,7 @@ use futures::executor::block_on; use futures::future::{Future, FutureExt}; -use futures::stream::{self, StreamExt, TryStreamExt}; use futures::io::{AsyncBufReadExt, Cursor}; +use futures::stream::{self, StreamExt, TryStreamExt}; use futures::task::Poll; use futures_test::io::AsyncReadTestExt; use futures_test::task::noop_context; diff --git a/futures/tests/io_write.rs b/futures/tests/io_write.rs index b96344446c..afca3c3fdc 100644 --- a/futures/tests/io_write.rs +++ b/futures/tests/io_write.rs @@ -57,14 +57,9 @@ fn write_vectored_first_non_empty() { Poll::Ready(Ok(4)) }); let cx = &mut panic_context(); - let bufs = &mut [ - io::IoSlice::new(&[]), - io::IoSlice::new(&[]), - io::IoSlice::new(b"four") - ]; + let bufs = &mut [io::IoSlice::new(&[]), io::IoSlice::new(&[]), io::IoSlice::new(b"four")]; let res = Pin::new(&mut writer).poll_write_vectored(cx, bufs); let res = res.map_err(|e| e.kind()); assert_eq!(res, Poll::Ready(Ok(4))); } - diff --git a/futures/tests/join_all.rs b/futures/tests/join_all.rs index 63967bf987..d0862bc57e 100644 --- a/futures/tests/join_all.rs +++ b/futures/tests/join_all.rs @@ -1,7 +1,7 @@ -use futures_util::future::*; -use std::future::Future; use futures::executor::block_on; +use futures_util::future::*; use std::fmt::Debug; +use std::future::Future; fn assert_done(actual_fut: F, expected: T) where @@ -31,7 +31,7 @@ fn join_all_iter_lifetime() { Box::new(join_all(iter)) } - assert_done(|| sizes(vec![&[1,2,3], &[], &[0]]), vec![3 as usize, 0, 1]); + assert_done(|| sizes(vec![&[1, 2, 3], &[], &[0]]), vec![3 as usize, 0, 1]); } #[test] diff --git a/futures/tests/mutex.rs b/futures/tests/mutex.rs index bad53a9b8f..d19d9883b4 100644 --- a/futures/tests/mutex.rs +++ b/futures/tests/mutex.rs @@ -37,10 +37,7 @@ fn mutex_wakes_waiters() { #[test] fn mutex_contested() { let (tx, mut rx) = mpsc::unbounded(); - let pool = futures::executor::ThreadPool::builder() - .pool_size(16) - .create() - .unwrap(); + let pool = futures::executor::ThreadPool::builder().pool_size(16).create().unwrap(); let tx = Arc::new(tx); let mutex = Arc::new(Mutex::new(0)); diff --git a/futures/tests/recurse.rs b/futures/tests/recurse.rs index 2920a41a59..c62f17fa8e 100644 --- a/futures/tests/recurse.rs +++ b/futures/tests/recurse.rs @@ -1,5 +1,5 @@ use futures::executor::block_on; -use futures::future::{self, FutureExt, BoxFuture}; +use futures::future::{self, BoxFuture, FutureExt}; use std::sync::mpsc; use std::thread; @@ -15,8 +15,6 @@ fn lots() { } let (tx, rx) = mpsc::channel(); - thread::spawn(|| { - block_on(do_it((1_000, 0)).map(move |x| tx.send(x).unwrap())) - }); + thread::spawn(|| block_on(do_it((1_000, 0)).map(move |x| tx.send(x).unwrap()))); assert_eq!(500_500, rx.recv().unwrap()); } diff --git a/futures/tests/select_all.rs b/futures/tests/select_all.rs index aad977d351..299b479044 100644 --- a/futures/tests/select_all.rs +++ b/futures/tests/select_all.rs @@ -4,11 +4,7 @@ use std::collections::HashSet; #[test] fn smoke() { - let v = vec![ - ready(1), - ready(2), - ready(3), - ]; + let v = vec![ready(1), ready(2), ready(3)]; let mut c = vec![1, 2, 3].into_iter().collect::>(); diff --git a/futures/tests/select_ok.rs b/futures/tests/select_ok.rs index db88a95c7a..8aec00362d 100644 --- a/futures/tests/select_ok.rs +++ b/futures/tests/select_ok.rs @@ -3,12 +3,7 @@ use futures::future::{err, ok, select_ok}; #[test] fn ignore_err() { - let v = vec![ - err(1), - err(2), - ok(3), - ok(4), - ]; + let v = vec![err(1), err(2), ok(3), ok(4)]; let (i, v) = block_on(select_ok(v)).ok().unwrap(); assert_eq!(i, 3); @@ -23,11 +18,7 @@ fn ignore_err() { #[test] fn last_err() { - let v = vec![ - ok(1), - err(2), - err(3), - ]; + let v = vec![ok(1), err(2), err(3)]; let (i, v) = block_on(select_ok(v)).ok().unwrap(); assert_eq!(i, 1); diff --git a/futures/tests/shared.rs b/futures/tests/shared.rs index 8402bfe10b..1199df3a0e 100644 --- a/futures/tests/shared.rs +++ b/futures/tests/shared.rs @@ -1,6 +1,6 @@ use futures::channel::oneshot; use futures::executor::{block_on, LocalPool}; -use futures::future::{self, FutureExt, TryFutureExt, LocalFutureObj}; +use futures::future::{self, FutureExt, LocalFutureObj, TryFutureExt}; use futures::task::LocalSpawn; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -77,7 +77,8 @@ fn drop_in_poll() { let future1 = future::lazy(move |_| { slot2.replace(None); // Drop future 1 - }).shared(); + }) + .shared(); let future2 = LocalFutureObj::new(Box::new(future1.clone())); slot1.replace(Some(future2)); diff --git a/futures/tests/sink.rs b/futures/tests/sink.rs index f967e1b643..1ee674280d 100644 --- a/futures/tests/sink.rs +++ b/futures/tests/sink.rs @@ -13,8 +13,8 @@ use std::fmt; use std::mem; use std::pin::Pin; use std::rc::Rc; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; fn sassert_next(s: &mut S, item: S::Item) where @@ -38,11 +38,8 @@ fn unwrap(x: Poll>) -> T { #[test] fn either_sink() { - let mut s = if true { - Vec::::new().left_sink() - } else { - VecDeque::::new().right_sink() - }; + let mut s = + if true { Vec::::new().left_sink() } else { VecDeque::::new().right_sink() }; Pin::new(&mut s).start_send(0).unwrap(); } @@ -288,10 +285,7 @@ impl Sink> for ManualFlush { impl ManualFlush { fn new() -> Self { - Self { - data: Vec::new(), - waiting_tasks: Vec::new(), - } + Self { data: Vec::new(), waiting_tasks: Vec::new() } } fn force_flush(&mut self) -> Vec { @@ -350,10 +344,7 @@ struct Allow { impl Allow { fn new() -> Self { - Self { - flag: Cell::new(false), - tasks: RefCell::new(Vec::new()), - } + Self { flag: Cell::new(false), tasks: RefCell::new(Vec::new()) } } fn check(&self, cx: &mut Context<'_>) -> bool { @@ -401,10 +392,7 @@ impl Sink for ManualAllow { fn manual_allow() -> (ManualAllow, Rc) { let allow = Rc::new(Allow::new()); - let manual_allow = ManualAllow { - data: Vec::new(), - allow: allow.clone(), - }; + let manual_allow = ManualAllow { data: Vec::new(), allow: allow.clone() }; (manual_allow, allow) } @@ -483,10 +471,7 @@ fn sink_map_err() { } let tx = mpsc::channel(0).0; - assert_eq!( - Pin::new(&mut tx.sink_map_err(|_| ())).start_send(()), - Err(()) - ); + assert_eq!(Pin::new(&mut tx.sink_map_err(|_| ())).start_send(()), Err(())); } #[derive(Copy, Clone, Debug, PartialEq, Eq)] @@ -509,8 +494,5 @@ fn err_into() { } let tx = mpsc::channel(0).0; - assert_eq!( - Pin::new(&mut tx.sink_err_into()).start_send(()), - Err(ErrIntoTest) - ); + assert_eq!(Pin::new(&mut tx.sink_err_into()).start_send(()), Err(ErrIntoTest)); } diff --git a/futures/tests/split.rs b/futures/tests/split.rs index 9f4f1a07e2..bf3521265d 100644 --- a/futures/tests/split.rs +++ b/futures/tests/split.rs @@ -7,7 +7,7 @@ use std::pin::Pin; struct Join { stream: T, - sink: U + sink: U, } impl Join { @@ -18,10 +18,7 @@ impl Join { impl Stream for Join { type Item = T::Item; - fn poll_next( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.stream().poll_next(cx) } } @@ -29,31 +26,19 @@ impl Stream for Join { impl, Item> Sink for Join { type Error = U::Error; - fn poll_ready( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.sink().poll_ready(cx) } - fn start_send( - self: Pin<&mut Self>, - item: Item, - ) -> Result<(), Self::Error> { + fn start_send(self: Pin<&mut Self>, item: Item) -> Result<(), Self::Error> { self.sink().start_send(item) } - fn poll_flush( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.sink().poll_flush(cx) } - fn poll_close( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.sink().poll_close(cx) } } @@ -62,10 +47,7 @@ impl, Item> Sink for Join { fn test_split() { let mut dest: Vec = Vec::new(); { - let join = Join { - stream: stream::iter(vec![10, 20, 30]), - sink: &mut dest - }; + let join = Join { stream: stream::iter(vec![10, 20, 30]), sink: &mut dest }; let (sink, stream) = join.split(); let join = sink.reunite(stream).expect("test_split: reunite error"); diff --git a/futures/tests/stream.rs b/futures/tests/stream.rs index fd6a8b6da7..54f49c668d 100644 --- a/futures/tests/stream.rs +++ b/futures/tests/stream.rs @@ -20,9 +20,9 @@ fn scan() { futures::executor::block_on(async { assert_eq!( stream::iter(vec![1u8, 2, 3, 4, 6, 8, 2]) - .scan(1, |acc, e| { - *acc += 1; - futures::future::ready(if e < *acc { Some(e) } else { None }) + .scan(1, |state, e| { + *state += 1; + futures::future::ready(if e < *state { Some(e) } else { None }) }) .collect::>() .await, diff --git a/futures/tests/stream_into_async_read.rs b/futures/tests/stream_into_async_read.rs index c528af03f0..35d0c91cde 100644 --- a/futures/tests/stream_into_async_read.rs +++ b/futures/tests/stream_into_async_read.rs @@ -1,8 +1,8 @@ use core::pin::Pin; -use futures::io::{AsyncRead, AsyncBufRead}; +use futures::io::{AsyncBufRead, AsyncRead}; use futures::stream::{self, TryStreamExt}; use futures::task::Poll; -use futures_test::{task::noop_context, stream::StreamTestExt}; +use futures_test::{stream::StreamTestExt, task::noop_context}; macro_rules! assert_read { ($reader:expr, $buf:expr, $item:expr) => { diff --git a/futures/tests/stream_select_next_some.rs b/futures/tests/stream_select_next_some.rs index 09d7e895c1..88b3e99839 100644 --- a/futures/tests/stream_select_next_some.rs +++ b/futures/tests/stream_select_next_some.rs @@ -1,7 +1,7 @@ -use futures::{future, select}; use futures::future::{FusedFuture, FutureExt}; use futures::stream::{FuturesUnordered, StreamExt}; use futures::task::{Context, Poll}; +use futures::{future, select}; use futures_test::future::FutureTestExt; use futures_test::task::new_count_waker; diff --git a/futures/tests/try_join.rs b/futures/tests/try_join.rs index 6c6d0843d5..8b0b38c1a3 100644 --- a/futures/tests/try_join.rs +++ b/futures/tests/try_join.rs @@ -1,6 +1,6 @@ #![deny(unreachable_code)] -use futures::{try_join, executor::block_on}; +use futures::{executor::block_on, try_join}; // TODO: This abuses https://github.com/rust-lang/rust/issues/58733 in order to // test behaviour of the `try_join!` macro with the never type before it is @@ -14,7 +14,6 @@ impl MyTrait for fn() -> T { } type Never = ! as MyTrait>::Output; - #[test] fn try_join_never_error() { block_on(async { diff --git a/futures/tests/try_join_all.rs b/futures/tests/try_join_all.rs index 662b866ec8..7186458a6a 100644 --- a/futures/tests/try_join_all.rs +++ b/futures/tests/try_join_all.rs @@ -1,7 +1,7 @@ -use futures_util::future::*; -use std::future::Future; use futures::executor::block_on; +use futures_util::future::*; use std::fmt::Debug; +use std::future::Future; fn assert_done(actual_fut: F, expected: T) where @@ -32,7 +32,7 @@ fn try_join_all_iter_lifetime() { Box::new(try_join_all(iter)) } - assert_done(|| sizes(vec![&[1,2,3], &[], &[0]]), Ok(vec![3 as usize, 0, 1])); + assert_done(|| sizes(vec![&[1, 2, 3], &[], &[0]]), Ok(vec![3 as usize, 0, 1])); } #[test] diff --git a/futures/tests/unfold.rs b/futures/tests/unfold.rs index 95722cf8a6..944446401e 100644 --- a/futures/tests/unfold.rs +++ b/futures/tests/unfold.rs @@ -2,9 +2,7 @@ use futures::future; use futures::stream; use futures_test::future::FutureTestExt; -use futures_test::{ - assert_stream_done, assert_stream_next, assert_stream_pending, -}; +use futures_test::{assert_stream_done, assert_stream_next, assert_stream_pending}; #[test] fn unfold1() {