diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 210b9767f3d..9c583a086e9 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -11,6 +11,12 @@ jobs: rust: $(nightly) name: rustfmt +# Apply clippy lints to all crates +- template: ci/azure-clippy.yml + parameters: + rust: $(nightly) + name: clippy + # Test top level crate - template: ci/azure-test-stable.yml parameters: diff --git a/ci/azure-clippy.yml b/ci/azure-clippy.yml new file mode 100644 index 00000000000..11a1cf75138 --- /dev/null +++ b/ci/azure-clippy.yml @@ -0,0 +1,16 @@ +jobs: +- job: ${{ parameters.name }} + displayName: Clippy + pool: + vmImage: ubuntu-16.04 + steps: + - template: azure-install-rust.yml + parameters: + rust_version: ${{ parameters.rust }} + - script: | + rustup component add clippy + cargo clippy --version + displayName: Install clippy + - script: | + cargo clippy --all --all-features -- -D warnings -A clippy::mutex-atomic + displayName: cargo clippy --all diff --git a/tokio-codec/src/bytes_codec.rs b/tokio-codec/src/bytes_codec.rs index b4a0fa31a81..c5bf62b8007 100644 --- a/tokio-codec/src/bytes_codec.rs +++ b/tokio-codec/src/bytes_codec.rs @@ -4,7 +4,7 @@ use bytes::{BufMut, Bytes, BytesMut}; use std::io; /// A simple `Codec` implementation that just ships bytes around. -#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Default)] pub struct BytesCodec(()); impl BytesCodec { @@ -19,7 +19,7 @@ impl Decoder for BytesCodec { type Error = io::Error; fn decode(&mut self, buf: &mut BytesMut) -> Result, io::Error> { - if buf.len() > 0 { + if !buf.is_empty() { let len = buf.len(); Ok(Some(buf.split_to(len))) } else { diff --git a/tokio-codec/src/framed_read.rs b/tokio-codec/src/framed_read.rs index 163a59bac48..25fc26b418f 100644 --- a/tokio-codec/src/framed_read.rs +++ b/tokio-codec/src/framed_read.rs @@ -153,7 +153,7 @@ pub fn framed_read2_with_buffer(inner: T, mut buf: BytesMut) -> FramedRead2 0, + is_readable: !buf.is_empty(), buffer: buf, } } diff --git a/tokio-codec/src/lines_codec.rs b/tokio-codec/src/lines_codec.rs index 4f7b08e7500..31c5990ebab 100644 --- a/tokio-codec/src/lines_codec.rs +++ b/tokio-codec/src/lines_codec.rs @@ -190,6 +190,12 @@ impl Encoder for LinesCodec { } } +impl Default for LinesCodec { + fn default() -> Self { + Self::new() + } +} + /// An error occured while encoding or decoding a line. #[derive(Debug)] pub enum LinesCodecError { diff --git a/tokio-current-thread/src/lib.rs b/tokio-current-thread/src/lib.rs index 21283e93fd2..009b1372475 100644 --- a/tokio-current-thread/src/lib.rs +++ b/tokio-current-thread/src/lib.rs @@ -348,7 +348,7 @@ impl CurrentThread

{ } /// Bind `CurrentThread` instance with an execution context. - fn enter<'a>(&'a mut self) -> Entered<'a, P> { + fn enter(&mut self) -> Entered<'_, P> { Entered { executor: self } } @@ -429,6 +429,12 @@ impl fmt::Debug for CurrentThread

{ } } +impl Default for CurrentThread

{ + fn default() -> Self { + CurrentThread::new_with_park(P::default()) + } +} + // ===== impl Entered ===== impl<'a, P: Park> Entered<'a, P> { @@ -483,7 +489,7 @@ impl<'a, P: Park> Entered<'a, P> { self.tick(); - if let Err(_) = self.executor.park.park() { + if self.executor.park.park().is_err() { panic!("block_on park failed"); } } @@ -550,7 +556,7 @@ impl<'a, P: Park> Entered<'a, P> { match time { Some((until, rem)) => { - if let Err(_) = self.executor.park.park_timeout(rem) { + if self.executor.park.park_timeout(rem).is_err() { return Err(RunTimeoutError::new(false)); } @@ -563,7 +569,7 @@ impl<'a, P: Park> Entered<'a, P> { time = Some((until, until - now)); } None => { - if let Err(_) = self.executor.park.park() { + if self.executor.park.park().is_err() { return Err(RunTimeoutError::new(false)); } } @@ -790,6 +796,8 @@ impl CurrentRunner { unsafe fn hide_lt<'a>(p: *mut (dyn SpawnLocal + 'a)) -> *mut (dyn SpawnLocal + 'static) { use std::mem; + // false positive: https://github.com/rust-lang/rust-clippy/issues/2906 + #[allow(clippy::transmute_ptr_to_ptr)] mem::transmute(p) } diff --git a/tokio-current-thread/src/scheduler.rs b/tokio-current-thread/src/scheduler.rs index 481e62985d3..29dc42e41a5 100644 --- a/tokio-current-thread/src/scheduler.rs +++ b/tokio-current-thread/src/scheduler.rs @@ -443,10 +443,8 @@ impl Inner { let tail = *self.tail_readiness.get(); let next = (*tail).next_readiness.load(Acquire); - if tail == self.stub() { - if next.is_null() { - return false; - } + if tail == self.stub() && next.is_null() { + return false; } true @@ -566,7 +564,7 @@ impl List { self.len += 1; - return ptr; + ptr } /// Pop an element from the front of the list @@ -618,7 +616,7 @@ impl List { self.len -= 1; - return node; + node } } @@ -773,7 +771,7 @@ impl Drop for Node { fn arc2ptr(ptr: Arc) -> *const T { let addr = &*ptr as *const T; mem::forget(ptr); - return addr; + addr } unsafe fn ptr2arc(ptr: *const T) -> Arc { diff --git a/tokio-executor/src/global.rs b/tokio-executor/src/global.rs index 49eeed80fae..6017d5f7348 100644 --- a/tokio-executor/src/global.rs +++ b/tokio-executor/src/global.rs @@ -180,6 +180,8 @@ where unsafe fn hide_lt<'a>(p: *mut (dyn Executor + 'a)) -> *mut (dyn Executor + 'static) { use std::mem; + // false positive: https://github.com/rust-lang/rust-clippy/issues/2906 + #[allow(clippy::transmute_ptr_to_ptr)] mem::transmute(p) } diff --git a/tokio-executor/src/park.rs b/tokio-executor/src/park.rs index 35cd846b42e..e5d6acf4bca 100644 --- a/tokio-executor/src/park.rs +++ b/tokio-executor/src/park.rs @@ -218,6 +218,12 @@ impl Park for ParkThread { } } +impl Default for ParkThread { + fn default() -> Self { + Self::new() + } +} + // ===== impl UnparkThread ===== impl Unpark for UnparkThread { diff --git a/tokio-fs/src/file/open_options.rs b/tokio-fs/src/file/open_options.rs index 124feb17e63..1a4f63c51c8 100644 --- a/tokio-fs/src/file/open_options.rs +++ b/tokio-fs/src/file/open_options.rs @@ -102,3 +102,9 @@ impl From for OpenOptions { OpenOptions(options) } } + +impl Default for OpenOptions { + fn default() -> Self { + Self::new() + } +} diff --git a/tokio-io/src/async_read.rs b/tokio-io/src/async_read.rs index 1b7eaa6cea0..1a59692f44d 100644 --- a/tokio-io/src/async_read.rs +++ b/tokio-io/src/async_read.rs @@ -62,8 +62,8 @@ pub trait AsyncRead { /// [`io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html /// [`poll_read_buf`]: #method.poll_read_buf unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool { - for i in 0..buf.len() { - buf[i] = 0; + for x in buf { + *x = 0; } true diff --git a/tokio-macros/src/lib.rs b/tokio-macros/src/lib.rs index 3a7b9ec42fd..2d24dd9a8ed 100644 --- a/tokio-macros/src/lib.rs +++ b/tokio-macros/src/lib.rs @@ -66,15 +66,12 @@ pub fn main(args: TokenStream, item: TokenStream) -> TokenStream { let mut runtime = RuntimeType::Multi; for arg in args { - match arg { - syn::NestedMeta::Meta(syn::Meta::Word(ident)) => { - match ident.to_string().to_lowercase().as_str() { - "multi_thread" => runtime = RuntimeType::Multi, - "single_thread" => runtime = RuntimeType::Single, - name => panic!("Unknown attribute {} is specified", name), - } + if let syn::NestedMeta::Meta(syn::Meta::Word(ident)) = arg { + match ident.to_string().to_lowercase().as_str() { + "multi_thread" => runtime = RuntimeType::Multi, + "single_thread" => runtime = RuntimeType::Single, + name => panic!("Unknown attribute {} is specified", name), } - _ => (), } } diff --git a/tokio-reactor/src/lib.rs b/tokio-reactor/src/lib.rs index 29db1faaab1..64f34e139d3 100644 --- a/tokio-reactor/src/lib.rs +++ b/tokio-reactor/src/lib.rs @@ -322,7 +322,7 @@ impl Reactor { "loop process - {} events, {}.{:03}s", events, dur.as_secs(), - dur.subsec_nanos() / 1_000_000 + dur.subsec_millis() ); } @@ -352,7 +352,7 @@ impl Reactor { io.readiness.fetch_or(ready.as_usize(), Relaxed); - if ready.is_writable() || platform::is_hup(&ready) { + if ready.is_writable() || platform::is_hup(ready) { wr = io.writer.take_waker(); } @@ -570,8 +570,8 @@ impl Drop for Inner { } impl Direction { - fn mask(&self) -> mio::Ready { - match *self { + fn mask(self) -> mio::Ready { + match self { Direction::Read => { // Everything except writable is signaled through read. mio::Ready::all() - mio::Ready::writable() @@ -590,8 +590,8 @@ mod platform { UnixReady::hup().into() } - pub fn is_hup(ready: &Ready) -> bool { - UnixReady::from(*ready).is_hup() + pub fn is_hup(ready: Ready) -> bool { + UnixReady::from(ready).is_hup() } } @@ -603,7 +603,7 @@ mod platform { Ready::empty() } - pub fn is_hup(_: &Ready) -> bool { + pub fn is_hup(_: Ready) -> bool { false } } diff --git a/tokio-reactor/src/poll_evented.rs b/tokio-reactor/src/poll_evented.rs index 50f21434f43..2b62d352795 100644 --- a/tokio-reactor/src/poll_evented.rs +++ b/tokio-reactor/src/poll_evented.rs @@ -257,7 +257,7 @@ where // Cannot clear write readiness assert!(!ready.is_writable(), "cannot clear write readiness"); assert!( - !crate::platform::is_hup(&ready), + !crate::platform::is_hup(ready), "cannot clear HUP readiness" ); diff --git a/tokio-reactor/src/registration.rs b/tokio-reactor/src/registration.rs index 9592f6c80bf..940b19e6f92 100644 --- a/tokio-reactor/src/registration.rs +++ b/tokio-reactor/src/registration.rs @@ -114,7 +114,7 @@ impl Registration { where T: Evented, { - self.register2(io, || HandlePriv::try_current()) + self.register2(io, HandlePriv::try_current) } /// Deregister the I/O resource from the reactor it is associated with. @@ -416,6 +416,12 @@ impl Registration { } } +impl Default for Registration { + fn default() -> Self { + Self::new() + } +} + unsafe impl Send for Registration {} unsafe impl Sync for Registration {} diff --git a/tokio-signal/src/registry.rs b/tokio-signal/src/registry.rs index 5705fc1a631..215deceaabf 100644 --- a/tokio-signal/src/registry.rs +++ b/tokio-signal/src/registry.rs @@ -76,9 +76,9 @@ impl Registry { /// Mark `event_id` as having been delivered, without broadcasting it to /// any listeners. fn record_event(&self, event_id: EventId) { - self.storage - .event_info(event_id) - .map(|event_info| event_info.pending.store(true, Ordering::SeqCst)); + if let Some(event_info) = self.storage.event_info(event_id) { + event_info.pending.store(true, Ordering::SeqCst) + } } /// Broadcast all previously recorded events to their respective listeners. diff --git a/tokio-sync/src/mpsc/bounded.rs b/tokio-sync/src/mpsc/bounded.rs index c549f5498f7..4e32a1ce4a0 100644 --- a/tokio-sync/src/mpsc/bounded.rs +++ b/tokio-sync/src/mpsc/bounded.rs @@ -132,6 +132,7 @@ impl Receiver { } /// TODO: Dox + #[allow(clippy::needless_lifetimes)] // false positive: https://github.com/rust-lang/rust-clippy/issues/3988 pub async fn recv(&mut self) -> Option { use async_util::future::poll_fn; @@ -204,6 +205,7 @@ impl Sender { /// ``` /// unimplemented!(); /// ``` + #[allow(clippy::needless_lifetimes)] // false positive: https://github.com/rust-lang/rust-clippy/issues/3988 pub async fn send(&mut self, value: T) -> Result<(), SendError> { use async_util::future::poll_fn; diff --git a/tokio-sync/src/mpsc/unbounded.rs b/tokio-sync/src/mpsc/unbounded.rs index dd1664a467c..9de0ae12fa0 100644 --- a/tokio-sync/src/mpsc/unbounded.rs +++ b/tokio-sync/src/mpsc/unbounded.rs @@ -93,6 +93,7 @@ impl UnboundedReceiver { } /// TODO: Dox + #[allow(clippy::needless_lifetimes)] // false positive: https://github.com/rust-lang/rust-clippy/issues/3988 pub async fn recv(&mut self) -> Option { use async_util::future::poll_fn; diff --git a/tokio-sync/src/oneshot.rs b/tokio-sync/src/oneshot.rs index 179e45e8e1a..a51f8028948 100644 --- a/tokio-sync/src/oneshot.rs +++ b/tokio-sync/src/oneshot.rs @@ -220,6 +220,7 @@ impl Sender { /// ``` /// unimplemented!(); /// ``` + #[allow(clippy::needless_lifetimes)] // false positive: https://github.com/rust-lang/rust-clippy/issues/3988 pub async fn closed(&mut self) { use async_util::future::poll_fn; @@ -384,10 +385,10 @@ impl Inner { None => Ready(Err(RecvError(()))), } } else { - return Pending; + Pending } } else { - return Pending; + Pending } } } @@ -498,7 +499,7 @@ impl State { State(0) } - fn is_complete(&self) -> bool { + fn is_complete(self) -> bool { self.0 & VALUE_SENT == VALUE_SENT } @@ -510,7 +511,7 @@ impl State { State(val) } - fn is_rx_task_set(&self) -> bool { + fn is_rx_task_set(self) -> bool { self.0 & RX_TASK_SET == RX_TASK_SET } @@ -524,7 +525,7 @@ impl State { State(val & !RX_TASK_SET) } - fn is_closed(&self) -> bool { + fn is_closed(self) -> bool { self.0 & CLOSED == CLOSED } @@ -545,7 +546,7 @@ impl State { State(val & !TX_TASK_SET) } - fn is_tx_task_set(&self) -> bool { + fn is_tx_task_set(self) -> bool { self.0 & TX_TASK_SET == TX_TASK_SET } diff --git a/tokio-sync/src/semaphore.rs b/tokio-sync/src/semaphore.rs index 4803085cdfc..4dcfddb9945 100644 --- a/tokio-sync/src/semaphore.rs +++ b/tokio-sync/src/semaphore.rs @@ -597,9 +597,9 @@ impl Permit { } match semaphore.poll_permit(Some((cx, self)))? { - Ready(v) => { + Ready(()) => { self.state = PermitState::Acquired; - Ready(Ok(v)) + Ready(Ok(())) } Pending => { self.state = PermitState::Waiting; @@ -671,6 +671,12 @@ impl Permit { } } +impl Default for Permit { + fn default() -> Self { + Self::new() + } +} + // ===== impl AcquireError ==== impl AcquireError { @@ -874,8 +880,9 @@ impl WaiterNode { NodeState::store(&self.state, Idle, Relaxed); } - fn into_non_null(arc: Arc) -> NonNull { - let ptr = Arc::into_raw(arc); + #[allow(clippy::wrong_self_convention)] // https://github.com/rust-lang/rust-clippy/issues/4293 + fn into_non_null(self: Arc) -> NonNull { + let ptr = Arc::into_raw(self); unsafe { NonNull::new_unchecked(ptr as *mut _) } } } @@ -921,7 +928,7 @@ impl SemState { } /// Returns the amount of remaining capacity - fn available_permits(&self) -> usize { + fn available_permits(self) -> usize { if !self.has_available_permits() { return 0; } @@ -930,11 +937,11 @@ impl SemState { } /// Returns true if the state has permits that can be claimed by a waiter. - fn has_available_permits(&self) -> bool { + fn has_available_permits(self) -> bool { self.0 & NUM_FLAG == NUM_FLAG } - fn has_waiter(&self, stub: &WaiterNode) -> bool { + fn has_waiter(self, stub: &WaiterNode) -> bool { !self.has_available_permits() && !self.is_stub(stub) } @@ -978,12 +985,12 @@ impl SemState { self.0 += permits << NUM_SHIFT; } - fn is_waiter(&self) -> bool { + fn is_waiter(self) -> bool { self.0 & NUM_FLAG == 0 } /// Returns the waiter, if one is set. - fn waiter(&self) -> Option> { + fn waiter(self) -> Option> { if self.is_waiter() { let waiter = NonNull::new(self.as_ptr()).expect("null pointer stored"); @@ -994,7 +1001,7 @@ impl SemState { } /// Assumes `self` represents a pointer - fn as_ptr(&self) -> *mut WaiterNode { + fn as_ptr(self) -> *mut WaiterNode { (self.0 & !CLOSED_FLAG) as *mut WaiterNode } @@ -1009,7 +1016,7 @@ impl SemState { self.0 = waiter; } - fn is_stub(&self, stub: &WaiterNode) -> bool { + fn is_stub(self, stub: &WaiterNode) -> bool { self.as_ptr() as usize == stub as *const _ as usize } @@ -1021,7 +1028,7 @@ impl SemState { } /// Swap the values - fn swap(&self, cell: &AtomicUsize, ordering: Ordering) -> SemState { + fn swap(self, cell: &AtomicUsize, ordering: Ordering) -> SemState { let prev = SemState(cell.swap(self.to_usize(), ordering)); debug_assert_eq!(prev.is_closed(), self.is_closed()); prev @@ -1029,7 +1036,7 @@ impl SemState { /// Compare and exchange the current value into the provided cell fn compare_exchange( - &self, + self, cell: &AtomicUsize, prev: SemState, success: Ordering, @@ -1054,12 +1061,12 @@ impl SemState { SemState(value) } - fn is_closed(&self) -> bool { + fn is_closed(self) -> bool { self.0 & CLOSED_FLAG == CLOSED_FLAG } /// Converts the state into a `usize` representation. - fn to_usize(&self) -> usize { + fn to_usize(self) -> usize { self.0 } } @@ -1108,7 +1115,7 @@ impl NodeState { } fn compare_exchange( - &self, + self, cell: &AtomicUsize, prev: NodeState, success: Ordering, @@ -1120,16 +1127,16 @@ impl NodeState { } /// Returns `true` if `self` represents a queued state. - fn is_queued(&self) -> bool { + fn is_queued(self) -> bool { use self::NodeState::*; - match *self { + match self { Queued | QueuedWaiting => true, _ => false, } } - fn to_usize(&self) -> usize { - *self as usize + fn to_usize(self) -> usize { + self as usize } } diff --git a/tokio-sync/src/watch.rs b/tokio-sync/src/watch.rs index 2e90154d5db..6efe437db3b 100644 --- a/tokio-sync/src/watch.rs +++ b/tokio-sync/src/watch.rs @@ -270,6 +270,7 @@ impl Receiver { /// Attempts to clone the latest value sent via the channel. /// /// This is equivalent to calling `Clone` on the value returned by `poll_ref`. + #[allow(clippy::map_clone)] // false positive: https://github.com/rust-lang/rust-clippy/issues/3274 pub fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll> { let item = ready!(self.poll_ref(cx)); Ready(item.map(|v_ref| v_ref.clone())) @@ -280,6 +281,7 @@ impl Receiver { impl futures_core::Stream for Receiver { type Item = T; + #[allow(clippy::map_clone)] // false positive: https://github.com/rust-lang/rust-clippy/issues/3274 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let item = ready!(self.poll_ref(cx)); Ready(item.map(|v_ref| v_ref.clone())) @@ -376,7 +378,7 @@ impl futures_sink::Sink for Sender { } fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> { - let _ = self.as_ref().get_ref().broadcast(item)?; + self.as_ref().get_ref().broadcast(item)?; Ok(()) } diff --git a/tokio-tcp/src/listener.rs b/tokio-tcp/src/listener.rs index 4eb39a65461..66392a699a7 100644 --- a/tokio-tcp/src/listener.rs +++ b/tokio-tcp/src/listener.rs @@ -124,6 +124,7 @@ impl TcpListener { /// ``` /// unimplemented!(); /// ``` + #[allow(clippy::needless_lifetimes)] // false positive: https://github.com/rust-lang/rust-clippy/issues/3988 pub async fn accept(&mut self) -> io::Result<(TcpStream, SocketAddr)> { use async_util::future::poll_fn; poll_fn(|cx| self.poll_accept(cx)).await diff --git a/tokio-tcp/src/split.rs b/tokio-tcp/src/split.rs index cafbd492671..a6b98f3427c 100644 --- a/tokio-tcp/src/split.rs +++ b/tokio-tcp/src/split.rs @@ -53,9 +53,9 @@ pub struct TcpStreamReadHalfMut<'a>(&'a TcpStream); #[derive(Debug)] pub struct TcpStreamWriteHalfMut<'a>(&'a TcpStream); -pub(crate) fn split_mut<'a>( - stream: &'a mut TcpStream, -) -> (TcpStreamReadHalfMut<'a>, TcpStreamWriteHalfMut<'a>) { +pub(crate) fn split_mut( + stream: &mut TcpStream, +) -> (TcpStreamReadHalfMut<'_>, TcpStreamWriteHalfMut<'_>) { ( TcpStreamReadHalfMut(&*stream), TcpStreamWriteHalfMut(&*stream), diff --git a/tokio-tcp/src/stream.rs b/tokio-tcp/src/stream.rs index 978e42fbe84..397906f299c 100644 --- a/tokio-tcp/src/stream.rs +++ b/tokio-tcp/src/stream.rs @@ -732,7 +732,7 @@ impl TcpStream { /// /// See the module level documenation of [`split`](super::split) for more /// details. - pub fn split_mut<'a>(&'a mut self) -> (TcpStreamReadHalfMut<'a>, TcpStreamWriteHalfMut<'a>) { + pub fn split_mut(&mut self) -> (TcpStreamReadHalfMut<'_>, TcpStreamWriteHalfMut<'_>) { split_mut(self) } diff --git a/tokio-test/src/clock.rs b/tokio-test/src/clock.rs index 37e6acc3c76..9c1ebb82edd 100644 --- a/tokio-test/src/clock.rs +++ b/tokio-test/src/clock.rs @@ -138,6 +138,12 @@ impl MockClock { } } +impl Default for MockClock { + fn default() -> Self { + Self::new() + } +} + impl Handle { pub(self) fn new(timer: Timer, time: MockTime) -> Self { Handle { timer, time } diff --git a/tokio-test/src/io.rs b/tokio-test/src/io.rs index 4e4ec1b3fb9..468190913c6 100644 --- a/tokio-test/src/io.rs +++ b/tokio-test/src/io.rs @@ -187,11 +187,8 @@ impl Inner { return Err(io::ErrorKind::BrokenPipe.into()); } - match self.action() { - Some(&mut Action::Wait(..)) => { - return Err(io::ErrorKind::WouldBlock.into()); - } - _ => {} + if let Some(&mut Action::Wait(..)) = self.action() { + return Err(io::ErrorKind::WouldBlock.into()); } for i in 0..self.actions.len() { diff --git a/tokio-test/src/task.rs b/tokio-test/src/task.rs index f8944a74e46..8462ae2d453 100644 --- a/tokio-test/src/task.rs +++ b/tokio-test/src/task.rs @@ -98,6 +98,12 @@ impl MockTask { } } +impl Default for MockTask { + fn default() -> Self { + Self::new() + } +} + impl ThreadWaker { fn new() -> Self { ThreadWaker { diff --git a/tokio-threadpool/src/builder.rs b/tokio-threadpool/src/builder.rs index ae53a30b3e6..0b8bf3b2900 100644 --- a/tokio-threadpool/src/builder.rs +++ b/tokio-threadpool/src/builder.rs @@ -420,3 +420,9 @@ impl fmt::Debug for Builder { .finish() } } + +impl Default for Builder { + fn default() -> Self { + Self::new() + } +} diff --git a/tokio-threadpool/src/config.rs b/tokio-threadpool/src/config.rs index 42fa13ddae4..31a951cec1d 100644 --- a/tokio-threadpool/src/config.rs +++ b/tokio-threadpool/src/config.rs @@ -14,9 +14,12 @@ pub(crate) struct Config { pub around_worker: Option, pub after_start: Option>, pub before_stop: Option>, - pub panic_handler: Option) + Send + Sync>>, + pub panic_handler: Option, } +// Define type alias to avoid clippy::type_complexity. +type PanicHandler = Arc) + Send + Sync>; + /// Max number of workers that can be part of a pool. This is the most that can /// fit in the scheduler state. Note, that this is the max number of **active** /// threads. There can be more standby threads. diff --git a/tokio-threadpool/src/park/default_park.rs b/tokio-threadpool/src/park/default_park.rs index 3a4380b50d6..dd071389402 100644 --- a/tokio-threadpool/src/park/default_park.rs +++ b/tokio-threadpool/src/park/default_park.rs @@ -72,6 +72,12 @@ impl Park for DefaultPark { } } +impl Default for DefaultPark { + fn default() -> Self { + Self::new() + } +} + // ===== impl DefaultUnpark ===== impl Unpark for DefaultUnpark { diff --git a/tokio-threadpool/src/pool/backup.rs b/tokio-threadpool/src/pool/backup.rs index cb7f7ff5c22..bba3a4f5c93 100644 --- a/tokio-threadpool/src/pool/backup.rs +++ b/tokio-threadpool/src/pool/backup.rs @@ -235,12 +235,12 @@ impl Backup { impl State { /// Returns a new, default, thread `State` - pub fn new() -> State { + pub(crate) fn new() -> State { State(0) } /// Returns true if the thread entry is pushed in the sleeper stack - pub fn is_pushed(&self) -> bool { + pub(crate) fn is_pushed(self) -> bool { self.0 & PUSHED == PUSHED } @@ -248,19 +248,19 @@ impl State { self.0 &= !PUSHED; } - pub fn is_running(&self) -> bool { + pub(crate) fn is_running(self) -> bool { self.0 & RUNNING == RUNNING } - pub fn set_running(&mut self) { + pub(crate) fn set_running(&mut self) { self.0 |= RUNNING; } - pub fn unset_running(&mut self) { + pub(crate) fn unset_running(&mut self) { self.0 &= !RUNNING; } - pub fn is_terminated(&self) -> bool { + pub(crate) fn is_terminated(self) -> bool { self.0 & TERMINATED == TERMINATED } diff --git a/tokio-threadpool/src/pool/backup_stack.rs b/tokio-threadpool/src/pool/backup_stack.rs index 0c3af37555d..52d7c3de7c8 100644 --- a/tokio-threadpool/src/pool/backup_stack.rs +++ b/tokio-threadpool/src/pool/backup_stack.rs @@ -93,10 +93,7 @@ impl BackupStack { /// * `Err(_)` is returned if the pool has been shutdown. pub fn pop(&self, entries: &[Backup], terminate: bool) -> Result, ()> { // Figure out the empty value - let terminal = match terminate { - true => TERMINATED, - false => EMPTY, - }; + let terminal = if terminate { TERMINATED } else { EMPTY }; let mut state: State = self.state.load(Acquire).into(); @@ -164,7 +161,7 @@ impl State { State(EMPTY.0) } - fn head(&self) -> BackupId { + fn head(self) -> BackupId { BackupId(self.0 & STACK_MASK) } diff --git a/tokio-threadpool/src/pool/state.rs b/tokio-threadpool/src/pool/state.rs index 8806c956633..d9da1cbbf7d 100644 --- a/tokio-threadpool/src/pool/state.rs +++ b/tokio-threadpool/src/pool/state.rs @@ -33,19 +33,19 @@ pub(crate) const MAX_FUTURES: usize = usize::MAX >> NUM_FUTURES_OFFSET; impl State { #[inline] - pub fn new() -> State { + pub(crate) fn new() -> State { State(0) } /// Returns the number of futures still pending completion. - pub fn num_futures(&self) -> usize { + pub(crate) fn num_futures(self) -> usize { self.0 >> NUM_FUTURES_OFFSET } /// Increment the number of futures pending completion. /// /// Returns false on failure. - pub fn inc_num_futures(&mut self) { + pub(crate) fn inc_num_futures(&mut self) { debug_assert!(self.num_futures() < MAX_FUTURES); debug_assert!(self.lifecycle() < Lifecycle::ShutdownNow); @@ -53,7 +53,7 @@ impl State { } /// Decrement the number of futures pending completion. - pub fn dec_num_futures(&mut self) { + pub(crate) fn dec_num_futures(&mut self) { let num_futures = self.num_futures(); if num_futures == 0 { @@ -69,19 +69,19 @@ impl State { } /// Set the number of futures pending completion to zero - pub fn clear_num_futures(&mut self) { - self.0 = self.0 & LIFECYCLE_MASK; + pub(crate) fn clear_num_futures(&mut self) { + self.0 &= LIFECYCLE_MASK; } - pub fn lifecycle(&self) -> Lifecycle { + pub(crate) fn lifecycle(self) -> Lifecycle { (self.0 & LIFECYCLE_MASK).into() } - pub fn set_lifecycle(&mut self, val: Lifecycle) { + pub(crate) fn set_lifecycle(&mut self, val: Lifecycle) { self.0 = (self.0 & NUM_FUTURES_MASK) | (val as usize); } - pub fn is_terminated(&self) -> bool { + pub(crate) fn is_terminated(self) -> bool { self.lifecycle() == Lifecycle::ShutdownNow && self.num_futures() == 0 } } diff --git a/tokio-threadpool/src/task/blocking.rs b/tokio-threadpool/src/task/blocking.rs index feb8e187dfa..2640149f0e8 100644 --- a/tokio-threadpool/src/task/blocking.rs +++ b/tokio-threadpool/src/task/blocking.rs @@ -393,7 +393,7 @@ impl State { State((capacity << NUM_SHIFT) | NUM_FLAG) } - fn remaining_capacity(&self) -> usize { + fn remaining_capacity(self) -> usize { if !self.has_remaining_capacity() { return 0; } @@ -401,15 +401,15 @@ impl State { self.0 >> 1 } - fn has_remaining_capacity(&self) -> bool { + fn has_remaining_capacity(self) -> bool { self.0 & NUM_FLAG == NUM_FLAG } - fn has_task(&self, stub: &Task) -> bool { + fn has_task(self, stub: &Task) -> bool { !(self.has_remaining_capacity() || self.is_stub(stub)) } - fn is_stub(&self, stub: &Task) -> bool { + fn is_stub(self, stub: &Task) -> bool { self.0 == stub as *const _ as usize } @@ -452,11 +452,11 @@ impl State { } } - fn is_ptr(&self) -> bool { + fn is_ptr(self) -> bool { self.0 & NUM_FLAG == 0 } - fn ptr(&self) -> Option<*const Task> { + fn ptr(self) -> Option<*const Task> { if self.is_ptr() { Some(self.0 as *const Task) } else { diff --git a/tokio-threadpool/src/task/blocking_state.rs b/tokio-threadpool/src/task/blocking_state.rs index 36f49d038f9..db419fccbca 100644 --- a/tokio-threadpool/src/task/blocking_state.rs +++ b/tokio-threadpool/src/task/blocking_state.rs @@ -18,26 +18,26 @@ const ALLOCATED: usize = 0b10; impl BlockingState { /// Create a new, default, `BlockingState`. - pub fn new() -> BlockingState { + pub(crate) fn new() -> BlockingState { BlockingState(0) } /// Returns `true` if the state represents the associated task being queued /// in the pending blocking capacity channel - pub fn is_queued(&self) -> bool { + pub(crate) fn is_queued(&self) -> bool { self.0 & QUEUED == QUEUED } /// Toggle the queued flag /// /// Returns the state before the flag has been toggled. - pub fn toggle_queued(state: &AtomicUsize, ordering: Ordering) -> BlockingState { + pub(crate) fn toggle_queued(state: &AtomicUsize, ordering: Ordering) -> BlockingState { state.fetch_xor(QUEUED, ordering).into() } /// Returns `true` if the state represents the associated task having been /// allocated capacity to block. - pub fn is_allocated(&self) -> bool { + pub(crate) fn is_allocated(&self) -> bool { self.0 & ALLOCATED == ALLOCATED } @@ -46,7 +46,7 @@ impl BlockingState { /// /// If this returns `true`, then the task has the ability to block for the /// duration of the `poll`. - pub fn consume_allocation(state: &AtomicUsize, ordering: Ordering) -> CanBlock { + pub(crate) fn consume_allocation(state: &AtomicUsize, ordering: Ordering) -> CanBlock { let state: Self = state.fetch_and(!ALLOCATED, ordering).into(); if state.is_allocated() { @@ -58,7 +58,7 @@ impl BlockingState { } } - pub fn notify_blocking(state: &AtomicUsize, ordering: Ordering) { + pub(crate) fn notify_blocking(state: &AtomicUsize, ordering: Ordering) { let prev: Self = state.fetch_xor(ALLOCATED | QUEUED, ordering).into(); debug_assert!(prev.is_queued()); diff --git a/tokio-threadpool/src/task/mod.rs b/tokio-threadpool/src/task/mod.rs index 86348f42c4f..0477dd517d2 100644 --- a/tokio-threadpool/src/task/mod.rs +++ b/tokio-threadpool/src/task/mod.rs @@ -134,12 +134,12 @@ impl Task { let mut g = Guard(fut, true); - let mut waker = arc_waker::waker(Arc::new(Waker { + let waker = arc_waker::waker(Arc::new(Waker { task: me.clone(), pool: pool.clone(), })); - let mut cx = Context::from_waker(&mut waker); + let mut cx = Context::from_waker(&waker); let ret = g.0.as_mut().unwrap().as_mut().poll(&mut cx); @@ -239,7 +239,7 @@ impl Task { pub fn schedule(me: &Arc, pool: &Arc) { if me.schedule2() { let task = me.clone(); - let _ = pool.submit(task, &pool); + pool.submit(task, &pool); } } diff --git a/tokio-threadpool/src/task/state.rs b/tokio-threadpool/src/task/state.rs index 3e00f89bc53..89430a9e728 100644 --- a/tokio-threadpool/src/task/state.rs +++ b/tokio-threadpool/src/task/state.rs @@ -27,11 +27,11 @@ impl State { /// /// Tasks start in the scheduled state as they are immediately scheduled on /// creation. - pub fn new() -> State { + pub(crate) fn new() -> State { State::Scheduled } - pub fn stub() -> State { + pub(crate) fn stub() -> State { State::Idle } } diff --git a/tokio-threadpool/src/thread_pool.rs b/tokio-threadpool/src/thread_pool.rs index 11da99f9a2f..121b4dd5015 100644 --- a/tokio-threadpool/src/thread_pool.rs +++ b/tokio-threadpool/src/thread_pool.rs @@ -198,6 +198,12 @@ impl Drop for ThreadPool { } } +impl Default for ThreadPool { + fn default() -> Self { + Self::new() + } +} + /* * TODO: Bring back diff --git a/tokio-threadpool/src/worker/mod.rs b/tokio-threadpool/src/worker/mod.rs index 30910ca718f..34ce41b96f8 100644 --- a/tokio-threadpool/src/worker/mod.rs +++ b/tokio-threadpool/src/worker/mod.rs @@ -622,7 +622,7 @@ impl Worker { // We obtained permission to push the worker into the // sleeper queue. - if let Err(_) = self.pool.push_sleeper(self.id.0) { + if self.pool.push_sleeper(self.id.0).is_err() { trace!(" sleeping -- push to stack failed; idx={}", self.id.0); // The push failed due to the pool being terminated. // diff --git a/tokio-threadpool/src/worker/stack.rs b/tokio-threadpool/src/worker/stack.rs index 2d02864a3b2..1d4dfad9df4 100644 --- a/tokio-threadpool/src/worker/stack.rs +++ b/tokio-threadpool/src/worker/stack.rs @@ -120,10 +120,7 @@ impl Stack { terminate: bool, ) -> Option<(usize, worker::State)> { // Figure out the empty value - let terminal = match terminate { - true => TERMINATED, - false => EMPTY, - }; + let terminal = if terminate { TERMINATED } else { EMPTY }; // If terminating, the max lifecycle *must* be `Signaled`, which is the // highest lifecycle. By passing the greatest possible lifecycle value, @@ -215,7 +212,7 @@ impl State { } #[inline] - fn head(&self) -> usize { + fn head(self) -> usize { self.0 & STACK_MASK } diff --git a/tokio-threadpool/src/worker/state.rs b/tokio-threadpool/src/worker/state.rs index 82789eb3d89..e8d35c332fc 100644 --- a/tokio-threadpool/src/worker/state.rs +++ b/tokio-threadpool/src/worker/state.rs @@ -35,7 +35,7 @@ pub(crate) enum Lifecycle { impl State { /// Returns true if the worker entry is pushed in the sleeper stack - pub fn is_pushed(&self) -> bool { + pub fn is_pushed(self) -> bool { self.0 & PUSHED_MASK == PUSHED_MASK } @@ -43,7 +43,7 @@ impl State { self.0 |= PUSHED_MASK } - pub fn is_notified(&self) -> bool { + pub fn is_notified(self) -> bool { use self::Lifecycle::*; match self.lifecycle() { @@ -52,7 +52,7 @@ impl State { } } - pub fn lifecycle(&self) -> Lifecycle { + pub fn lifecycle(self) -> Lifecycle { Lifecycle::from(self.0 & LIFECYCLE_MASK) } @@ -60,7 +60,7 @@ impl State { self.0 = (self.0 & !LIFECYCLE_MASK) | (val as usize) } - pub fn is_signaled(&self) -> bool { + pub fn is_signaled(self) -> bool { self.lifecycle() == Lifecycle::Signaled } diff --git a/tokio-timer/src/clock/clock.rs b/tokio-timer/src/clock/clock.rs deleted file mode 100644 index 50efeb496cf..00000000000 --- a/tokio-timer/src/clock/clock.rs +++ /dev/null @@ -1,136 +0,0 @@ -use crate::clock::Now; -use crate::timer; -use std::cell::Cell; -use std::fmt; -use std::sync::Arc; -use std::time::Instant; - -/// A handle to a source of time. -/// -/// `Clock` instances return [`Instant`] values corresponding to "now". The source -/// of these values is configurable. The default source is [`Instant::now`]. -/// -/// [`Instant`]: https://doc.rust-lang.org/std/time/struct.Instant.html -/// [`Instant::now`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.now -#[derive(Default, Clone)] -pub struct Clock { - now: Option>, -} - -thread_local! { - /// Thread-local tracking the current clock - static CLOCK: Cell> = Cell::new(None) -} - -/// Returns an `Instant` corresponding to "now". -/// -/// This function delegates to the source of time configured for the current -/// execution context. By default, this is `Instant::now()`. -/// -/// Note that, because the source of time is configurable, it is possible to -/// observe non-monotonic behavior when calling `now` from different -/// executors. -/// -/// See [module](index.html) level documentation for more details. -/// -/// # Examples -/// -/// ``` -/// # use tokio_timer::clock; -/// let now = clock::now(); -/// ``` -pub fn now() -> Instant { - CLOCK.with(|current| match current.get() { - Some(ptr) => unsafe { (*ptr).now() }, - None => Instant::now(), - }) -} - -impl Clock { - /// Return a new `Clock` instance that uses the current execution context's - /// source of time. - pub fn new() -> Clock { - CLOCK.with(|current| match current.get() { - Some(ptr) => unsafe { (*ptr).clone() }, - None => Clock::system(), - }) - } - - /// Return a new `Clock` instance that uses `now` as the source of time. - pub fn new_with_now(now: T) -> Clock { - Clock { - now: Some(Arc::new(now)), - } - } - - /// Return a new `Clock` instance that uses [`Instant::now`] as the source - /// of time. - /// - /// [`Instant::now`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.now - pub fn system() -> Clock { - Clock { now: None } - } - - /// Returns an instant corresponding to "now" by using the instance's source - /// of time. - pub fn now(&self) -> Instant { - match self.now { - Some(ref now) => now.now(), - None => Instant::now(), - } - } -} - -#[allow(deprecated)] -impl timer::Now for Clock { - fn now(&mut self) -> Instant { - Clock::now(self) - } -} - -impl fmt::Debug for Clock { - fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_struct("Clock") - .field("now", { - if self.now.is_some() { - &"Some(Arc)" - } else { - &"None" - } - }) - .finish() - } -} - -/// Set the default clock for the duration of the closure. -/// -/// # Panics -/// -/// This function panics if there already is a default clock set. -pub fn with_default(clock: &Clock, f: F) -> R -where - F: FnOnce() -> R, -{ - CLOCK.with(|cell| { - assert!( - cell.get().is_none(), - "default clock already set for execution context" - ); - - // Ensure that the clock is removed from the thread-local context - // when leaving the scope. This handles cases that involve panicking. - struct Reset<'a>(&'a Cell>); - - impl<'a> Drop for Reset<'a> { - fn drop(&mut self) { - self.0.set(None); - } - } - - let _reset = Reset(cell); - - cell.set(Some(clock as *const Clock)); - - f() - }) -} diff --git a/tokio-timer/src/clock/mod.rs b/tokio-timer/src/clock/mod.rs index 1791bc75859..bcae9ddaad0 100644 --- a/tokio-timer/src/clock/mod.rs +++ b/tokio-timer/src/clock/mod.rs @@ -16,8 +16,142 @@ //! [`Instant::now`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.now //! [`with_default`]: fn.with_default.html -mod clock; mod now; -pub use self::clock::{now, with_default, Clock}; pub use self::now::Now; + +use crate::timer; +use std::cell::Cell; +use std::fmt; +use std::sync::Arc; +use std::time::Instant; + +/// A handle to a source of time. +/// +/// `Clock` instances return [`Instant`] values corresponding to "now". The source +/// of these values is configurable. The default source is [`Instant::now`]. +/// +/// [`Instant`]: https://doc.rust-lang.org/std/time/struct.Instant.html +/// [`Instant::now`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.now +#[derive(Default, Clone)] +pub struct Clock { + now: Option>, +} + +thread_local! { + /// Thread-local tracking the current clock + static CLOCK: Cell> = Cell::new(None) +} + +/// Returns an `Instant` corresponding to "now". +/// +/// This function delegates to the source of time configured for the current +/// execution context. By default, this is `Instant::now()`. +/// +/// Note that, because the source of time is configurable, it is possible to +/// observe non-monotonic behavior when calling `now` from different +/// executors. +/// +/// See [module](index.html) level documentation for more details. +/// +/// # Examples +/// +/// ``` +/// # use tokio_timer::clock; +/// let now = clock::now(); +/// ``` +pub fn now() -> Instant { + CLOCK.with(|current| match current.get() { + Some(ptr) => unsafe { (*ptr).now() }, + None => Instant::now(), + }) +} + +impl Clock { + /// Return a new `Clock` instance that uses the current execution context's + /// source of time. + pub fn new() -> Clock { + CLOCK.with(|current| match current.get() { + Some(ptr) => unsafe { (*ptr).clone() }, + None => Clock::system(), + }) + } + + /// Return a new `Clock` instance that uses `now` as the source of time. + pub fn new_with_now(now: T) -> Clock { + Clock { + now: Some(Arc::new(now)), + } + } + + /// Return a new `Clock` instance that uses [`Instant::now`] as the source + /// of time. + /// + /// [`Instant::now`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.now + pub fn system() -> Clock { + Clock { now: None } + } + + /// Returns an instant corresponding to "now" by using the instance's source + /// of time. + pub fn now(&self) -> Instant { + match self.now { + Some(ref now) => now.now(), + None => Instant::now(), + } + } +} + +#[allow(deprecated)] +impl timer::Now for Clock { + fn now(&mut self) -> Instant { + Clock::now(self) + } +} + +impl fmt::Debug for Clock { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt.debug_struct("Clock") + .field("now", { + if self.now.is_some() { + &"Some(Arc)" + } else { + &"None" + } + }) + .finish() + } +} + +/// Set the default clock for the duration of the closure. +/// +/// # Panics +/// +/// This function panics if there already is a default clock set. +pub fn with_default(clock: &Clock, f: F) -> R +where + F: FnOnce() -> R, +{ + CLOCK.with(|cell| { + assert!( + cell.get().is_none(), + "default clock already set for execution context" + ); + + // Ensure that the clock is removed from the thread-local context + // when leaving the scope. This handles cases that involve panicking. + struct Reset<'a>(&'a Cell>); + + impl<'a> Drop for Reset<'a> { + fn drop(&mut self) { + self.0.set(None); + } + } + + let _reset = Reset(cell); + + cell.set(Some(clock as *const Clock)); + + f() + }) +} diff --git a/tokio-timer/src/delay_queue.rs b/tokio-timer/src/delay_queue.rs index d9d0f36cb2c..32ae1c26ece 100644 --- a/tokio-timer/src/delay_queue.rs +++ b/tokio-timer/src/delay_queue.rs @@ -370,6 +370,8 @@ impl DelayQueue { } /// TODO: Dox... also is the fn signature correct? + #[allow(clippy::needless_lifetimes)] // false positive: https://github.com/rust-lang/rust-clippy/issues/3988 + #[allow(clippy::should_implement_trait)] // false positive : https://github.com/rust-lang/rust-clippy/issues/4290 pub async fn next(&mut self) -> Option, Error>> { use async_util::future::poll_fn; diff --git a/tokio-timer/src/interval.rs b/tokio-timer/src/interval.rs index f04486403b9..2d37647c593 100644 --- a/tokio-timer/src/interval.rs +++ b/tokio-timer/src/interval.rs @@ -72,6 +72,8 @@ impl Interval { } /// TODO: dox + #[allow(clippy::needless_lifetimes)] // false positive: https://github.com/rust-lang/rust-clippy/issues/3988 + #[allow(clippy::should_implement_trait)] // false positive : https://github.com/rust-lang/rust-clippy/issues/4290 pub async fn next(&mut self) -> Option { use async_util::future::poll_fn; diff --git a/tokio-timer/src/lib.rs b/tokio-timer/src/lib.rs index 36449472ce3..52e7e6c6ca7 100644 --- a/tokio-timer/src/lib.rs +++ b/tokio-timer/src/lib.rs @@ -81,11 +81,11 @@ fn ms(duration: Duration, round: Round) -> u64 { // Round up. let millis = match round { Round::Up => (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI, - Round::Down => duration.subsec_nanos() / NANOS_PER_MILLI, + Round::Down => duration.subsec_millis(), }; duration .as_secs() .saturating_mul(MILLIS_PER_SEC) - .saturating_add(millis as u64) + .saturating_add(u64::from(millis)) } diff --git a/tokio-timer/src/timer/atomic_stack.rs b/tokio-timer/src/timer/atomic_stack.rs index c248c20a1c7..6e091cbd90e 100644 --- a/tokio-timer/src/timer/atomic_stack.rs +++ b/tokio-timer/src/timer/atomic_stack.rs @@ -115,7 +115,7 @@ impl Iterator for AtomicStackEntries { impl Drop for AtomicStackEntries { fn drop(&mut self) { - while let Some(entry) = self.next() { + for entry in self { // Flag the entry as errored entry.error(); } diff --git a/tokio-timer/src/timer/entry.rs b/tokio-timer/src/timer/entry.rs index dc8288cf125..5d4d9808992 100644 --- a/tokio-timer/src/timer/entry.rs +++ b/tokio-timer/src/timer/entry.rs @@ -125,8 +125,9 @@ impl Entry { } /// Only called by `Registration` - pub fn time_mut(&self) -> &mut Time { - unsafe { &mut *self.time.get() } + #[allow(clippy::mut_from_ref)] // https://github.com/rust-lang/rust-clippy/issues/4281 + pub unsafe fn time_mut(&self) -> &mut Time { + &mut *self.time.get() } /// Returns `true` if the `Entry` is currently associated with a timer diff --git a/tokio-timer/src/timer/registration.rs b/tokio-timer/src/timer/registration.rs index d7604c86815..5e379d2353c 100644 --- a/tokio-timer/src/timer/registration.rs +++ b/tokio-timer/src/timer/registration.rs @@ -38,7 +38,9 @@ impl Registration { } pub fn reset(&mut self, deadline: Instant) { - self.entry.time_mut().deadline = deadline; + unsafe { + self.entry.time_mut().deadline = deadline; + } Entry::reset(&mut self.entry); } @@ -46,7 +48,9 @@ impl Registration { #[cfg(feature = "async-traits")] pub fn reset_timeout(&mut self) { let deadline = crate::clock::now() + self.entry.time_ref().duration; - self.entry.time_mut().deadline = deadline; + unsafe { + self.entry.time_mut().deadline = deadline; + } Entry::reset(&mut self.entry); } diff --git a/tokio-tls/src/lib.rs b/tokio-tls/src/lib.rs index f2730e2843a..b16f047363b 100644 --- a/tokio-tls/src/lib.rs +++ b/tokio-tls/src/lib.rs @@ -149,8 +149,7 @@ impl TlsStream { { self.0.get_mut().context = ctx as *mut _ as *mut (); let g = Guard(self); - let r = f(&mut (g.0).0); - r + f(&mut (g.0).0) } } @@ -193,8 +192,8 @@ where fn poll_shutdown(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll> { match self.with_context(ctx, |s| s.shutdown()) { Ok(()) => Poll::Ready(Ok(())), - Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => return Poll::Pending, - Err(e) => return Poll::Ready(Err(e)), + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Poll::Pending, + Err(e) => Poll::Ready(Err(e)), } } } @@ -289,6 +288,7 @@ impl TlsAcceptor { /// This is typically used after a new socket has been accepted from a /// `TcpListener`. That socket is then passed to this function to perform /// the server half of accepting a client connection. + #[allow(clippy::needless_lifetimes)] // false positive: https://github.com/rust-lang/rust-clippy/issues/3988 pub async fn accept(&self, stream: S) -> Result, Error> where S: AsyncRead + AsyncWrite + Unpin, diff --git a/tokio-udp/src/socket.rs b/tokio-udp/src/socket.rs index 9779004f040..5a3c94e8925 100644 --- a/tokio-udp/src/socket.rs +++ b/tokio-udp/src/socket.rs @@ -407,8 +407,8 @@ impl UdpSocket { /// address of the local interface with which the system should join the /// multicast group. If it's equal to `INADDR_ANY` then an appropriate /// interface is chosen by the system. - pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { - self.io.get_ref().join_multicast_v4(multiaddr, interface) + pub fn join_multicast_v4(&self, multiaddr: Ipv4Addr, interface: Ipv4Addr) -> io::Result<()> { + self.io.get_ref().join_multicast_v4(&multiaddr, &interface) } /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type. @@ -425,8 +425,8 @@ impl UdpSocket { /// For more information about this option, see [`join_multicast_v4`]. /// /// [`join_multicast_v4`]: #method.join_multicast_v4 - pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { - self.io.get_ref().leave_multicast_v4(multiaddr, interface) + pub fn leave_multicast_v4(&self, multiaddr: Ipv4Addr, interface: Ipv4Addr) -> io::Result<()> { + self.io.get_ref().leave_multicast_v4(&multiaddr, &interface) } /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type. diff --git a/tokio/src/codec/length_delimited.rs b/tokio/src/codec/length_delimited.rs index e319ba46150..b4822802b10 100644 --- a/tokio/src/codec/length_delimited.rs +++ b/tokio/src/codec/length_delimited.rs @@ -494,7 +494,7 @@ impl LengthDelimitedCodec { // payload src.reserve(n); - return Ok(Some(n)); + Ok(Some(n)) } fn decode_data(&self, n: usize, src: &mut BytesMut) -> io::Result> { @@ -584,6 +584,12 @@ impl Encoder for LengthDelimitedCodec { } } +impl Default for LengthDelimitedCodec { + fn default() -> Self { + Self::new() + } +} + // ===== impl Builder ===== impl Builder { @@ -930,6 +936,12 @@ impl Builder { } } +impl Default for Builder { + fn default() -> Self { + Self::new() + } +} + // ===== impl FrameTooBig ===== impl fmt::Debug for FrameTooBig { diff --git a/tokio/src/runtime/current_thread/builder.rs b/tokio/src/runtime/current_thread/builder.rs index ff8550f83ce..31a2ec3c818 100644 --- a/tokio/src/runtime/current_thread/builder.rs +++ b/tokio/src/runtime/current_thread/builder.rs @@ -82,3 +82,9 @@ impl Builder { Ok(runtime) } } + +impl Default for Builder { + fn default() -> Self { + Self::new() + } +} diff --git a/tokio/src/runtime/threadpool/builder.rs b/tokio/src/runtime/threadpool/builder.rs index 54c37691dea..f6b06b7d2fa 100644 --- a/tokio/src/runtime/threadpool/builder.rs +++ b/tokio/src/runtime/threadpool/builder.rs @@ -374,3 +374,9 @@ impl Builder { }) } } + +impl Default for Builder { + fn default() -> Self { + Self::new() + } +}