ci: enable clippy lints (#1335)

This commit is contained in:
Taiki Endo 2019-07-26 03:47:14 +09:00 committed by GitHub
parent f311ac3d4f
commit fe021e6c00
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
54 changed files with 394 additions and 274 deletions

View File

@ -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:

16
ci/azure-clippy.yml Normal file
View File

@ -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

View File

@ -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<Option<BytesMut>, io::Error> {
if buf.len() > 0 {
if !buf.is_empty() {
let len = buf.len();
Ok(Some(buf.split_to(len)))
} else {

View File

@ -153,7 +153,7 @@ pub fn framed_read2_with_buffer<T>(inner: T, mut buf: BytesMut) -> FramedRead2<T
FramedRead2 {
inner,
eof: false,
is_readable: buf.len() > 0,
is_readable: !buf.is_empty(),
buffer: buf,
}
}

View File

@ -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 {

View File

@ -348,7 +348,7 @@ impl<P: Park> CurrentThread<P> {
}
/// 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<P: Park> fmt::Debug for CurrentThread<P> {
}
}
impl<P: Park + Default> Default for CurrentThread<P> {
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)
}

View File

@ -443,10 +443,8 @@ impl<U> Inner<U> {
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<U> List<U> {
self.len += 1;
return ptr;
ptr
}
/// Pop an element from the front of the list
@ -618,7 +616,7 @@ impl<U> List<U> {
self.len -= 1;
return node;
node
}
}
@ -773,7 +771,7 @@ impl<U> Drop for Node<U> {
fn arc2ptr<T>(ptr: Arc<T>) -> *const T {
let addr = &*ptr as *const T;
mem::forget(ptr);
return addr;
addr
}
unsafe fn ptr2arc<T>(ptr: *const T) -> Arc<T> {

View File

@ -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)
}

View File

@ -218,6 +218,12 @@ impl Park for ParkThread {
}
}
impl Default for ParkThread {
fn default() -> Self {
Self::new()
}
}
// ===== impl UnparkThread =====
impl Unpark for UnparkThread {

View File

@ -102,3 +102,9 @@ impl From<StdOpenOptions> for OpenOptions {
OpenOptions(options)
}
}
impl Default for OpenOptions {
fn default() -> Self {
Self::new()
}
}

View File

@ -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

View File

@ -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),
}
_ => (),
}
}

View File

@ -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
}
}

View File

@ -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"
);

View File

@ -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 {}

View File

@ -76,9 +76,9 @@ impl<S: Storage> Registry<S> {
/// 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.

View File

@ -132,6 +132,7 @@ impl<T> Receiver<T> {
}
/// TODO: Dox
#[allow(clippy::needless_lifetimes)] // false positive: https://github.com/rust-lang/rust-clippy/issues/3988
pub async fn recv(&mut self) -> Option<T> {
use async_util::future::poll_fn;
@ -204,6 +205,7 @@ impl<T> Sender<T> {
/// ```
/// 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;

View File

@ -93,6 +93,7 @@ impl<T> UnboundedReceiver<T> {
}
/// TODO: Dox
#[allow(clippy::needless_lifetimes)] // false positive: https://github.com/rust-lang/rust-clippy/issues/3988
pub async fn recv(&mut self) -> Option<T> {
use async_util::future::poll_fn;

View File

@ -220,6 +220,7 @@ impl<T> Sender<T> {
/// ```
/// 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<T> Inner<T> {
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
}

View File

@ -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<WaiterNode>) -> NonNull<WaiterNode> {
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<WaiterNode>) -> NonNull<WaiterNode> {
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<NonNull<WaiterNode>> {
fn waiter(self) -> Option<NonNull<WaiterNode>> {
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
}
}

View File

@ -270,6 +270,7 @@ impl<T: Clone> Receiver<T> {
/// 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<Option<T>> {
let item = ready!(self.poll_ref(cx));
Ready(item.map(|v_ref| v_ref.clone()))
@ -280,6 +281,7 @@ impl<T: Clone> Receiver<T> {
impl<T: Clone> futures_core::Stream for Receiver<T> {
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<Option<T>> {
let item = ready!(self.poll_ref(cx));
Ready(item.map(|v_ref| v_ref.clone()))
@ -376,7 +378,7 @@ impl<T> futures_sink::Sink<T> for Sender<T> {
}
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(())
}

View File

@ -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

View File

@ -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),

View File

@ -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)
}

View File

@ -138,6 +138,12 @@ impl MockClock {
}
}
impl Default for MockClock {
fn default() -> Self {
Self::new()
}
}
impl Handle {
pub(self) fn new(timer: Timer<MockPark>, time: MockTime) -> Self {
Handle { timer, time }

View File

@ -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() {

View File

@ -98,6 +98,12 @@ impl MockTask {
}
}
impl Default for MockTask {
fn default() -> Self {
Self::new()
}
}
impl ThreadWaker {
fn new() -> Self {
ThreadWaker {

View File

@ -420,3 +420,9 @@ impl fmt::Debug for Builder {
.finish()
}
}
impl Default for Builder {
fn default() -> Self {
Self::new()
}
}

View File

@ -14,9 +14,12 @@ pub(crate) struct Config {
pub around_worker: Option<Callback>,
pub after_start: Option<Arc<dyn Fn() + Send + Sync>>,
pub before_stop: Option<Arc<dyn Fn() + Send + Sync>>,
pub panic_handler: Option<Arc<dyn Fn(Box<dyn Any + Send>) + Send + Sync>>,
pub panic_handler: Option<PanicHandler>,
}
// Define type alias to avoid clippy::type_complexity.
type PanicHandler = Arc<dyn Fn(Box<dyn Any + Send>) + 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.

View File

@ -72,6 +72,12 @@ impl Park for DefaultPark {
}
}
impl Default for DefaultPark {
fn default() -> Self {
Self::new()
}
}
// ===== impl DefaultUnpark =====
impl Unpark for DefaultUnpark {

View File

@ -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
}

View File

@ -93,10 +93,7 @@ impl BackupStack {
/// * `Err(_)` is returned if the pool has been shutdown.
pub fn pop(&self, entries: &[Backup], terminate: bool) -> Result<Option<BackupId>, ()> {
// 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)
}

View File

@ -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
}
}

View File

@ -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 {

View File

@ -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());

View File

@ -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<Self>, pool: &Arc<Pool>) {
if me.schedule2() {
let task = me.clone();
let _ = pool.submit(task, &pool);
pool.submit(task, &pool);
}
}

View File

@ -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
}
}

View File

@ -198,6 +198,12 @@ impl Drop for ThreadPool {
}
}
impl Default for ThreadPool {
fn default() -> Self {
Self::new()
}
}
/*
* TODO: Bring back

View File

@ -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.
//

View File

@ -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
}

View File

@ -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
}

View File

@ -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<Arc<dyn Now>>,
}
thread_local! {
/// Thread-local tracking the current clock
static CLOCK: Cell<Option<*const Clock>> = 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<T: 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<Now>)"
} 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<F, R>(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<Option<*const Clock>>);
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()
})
}

View File

@ -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<Arc<dyn Now>>,
}
thread_local! {
/// Thread-local tracking the current clock
static CLOCK: Cell<Option<*const Clock>> = 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<T: 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<Now>)"
} 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<F, R>(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<Option<*const Clock>>);
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()
})
}

View File

@ -370,6 +370,8 @@ impl<T> DelayQueue<T> {
}
/// 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<Result<Expired<T>, Error>> {
use async_util::future::poll_fn;

View File

@ -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<Instant> {
use async_util::future::poll_fn;

View File

@ -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))
}

View File

@ -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();
}

View File

@ -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

View File

@ -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);
}

View File

@ -149,8 +149,7 @@ impl<S> TlsStream<S> {
{
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<io::Result<()>> {
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<S>(&self, stream: S) -> Result<TlsStream<S>, Error>
where
S: AsyncRead + AsyncWrite + Unpin,

View File

@ -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.

View File

@ -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<Option<BytesMut>> {
@ -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 {

View File

@ -82,3 +82,9 @@ impl Builder {
Ok(runtime)
}
}
impl Default for Builder {
fn default() -> Self {
Self::new()
}
}

View File

@ -374,3 +374,9 @@ impl Builder {
})
}
}
impl Default for Builder {
fn default() -> Self {
Self::new()
}
}