From 5291175f382dabfef2f8a802f46f777c554b11da Mon Sep 17 00:00:00 2001 From: Roman Borschel Date: Fri, 17 Jul 2020 12:27:30 +0200 Subject: [PATCH 1/6] Spec-compliant noise handshake payloads (Step 1). (#1658) * Support spec-compliant reading of noise handshake payloads. See https://github.com/libp2p/rust-libp2p/issues/1631. This the first of a three-step process to addressing the issue. In this step, support for reading noise handshake payloads without an additional length prefix is added, falling back to attempting a decoding with length prefix on failure. Length prefixes are still sent in this step. Hence interoperability with other libp2p implementations is not yet achieved after with step. To achieve a better separation of handshake and transport I/O, the `NoiseFramed` type has been extracted from `NoiseOutput`. `NoiseFramed` is a `Sink` and `Stream` of length-delimited Noise protocol messages. This type is used in the handshake phase. Once a handshake completes the underlying Noise session transitions to transport mode and the `NoiseFramed` is wrapped in the `NoiseOutput` which provides a regular `AsyncRead` / `AsyncWrite` I/O resource on top of the framed encoding. No new buffers are introduced, they are just split between `NoiseFramed` and `NoiseOutput`. The second step involves removing the sending of the length prefix in a subsequent release. The third step involves removing the support for reading length-prefixed protobuf payloads. * Small cleanup. * Reuse frame decryption buffer. Since frames are consumed one-by-one, `NoiseFramed` can have a `BytesMut` decryption buffer, handing out immutable `Bytes` views for each decrypted message. Since each view gets fully consumed and dropped before the next frame is read, the `BytesMut` decryption buffer in `NoiseFramed` can always reuse the same buffer, only growing it as necessary. * Simplify. * Add missing inner poll_flush(). * Improve nested length detection. * Avoid unnecessary clearing of send buffers. Thus reducing the necessary zeroing of send buffers on resize, as per the previous behaviour. * Prepare release. --- CHANGELOG.md | 8 + Cargo.toml | 4 +- protocols/noise/CHANGELOG.md | 11 + protocols/noise/Cargo.toml | 7 +- protocols/noise/src/io.rs | 468 +++++----------------------- protocols/noise/src/io/framed.rs | 439 ++++++++++++++++++++++++++ protocols/noise/src/io/handshake.rs | 120 ++++--- 7 files changed, 612 insertions(+), 445 deletions(-) create mode 100644 protocols/noise/src/io/framed.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index ee75100c..c8be6676 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,14 @@ - [`parity-multiaddr` CHANGELOG](misc/multiaddr/CHANGELOG.md) - [`libp2p-core-derive` CHANGELOG](misc/core-derive/CHANGELOG.md) +# Version 0.22.0 (2020-07-17) + +**NOTE**: For a smooth upgrade path from `0.21` to `> 0.22` +on an existing deployment using `libp2p-noise`, this version +must not be skipped! + +- Bump `libp2p-noise` dependency to `0.21`. + # Version 0.21.1 (2020-07-02) - Bump `libp2p-websockets` lower bound. diff --git a/Cargo.toml b/Cargo.toml index 9363e738..ea73c741 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "libp2p" edition = "2018" description = "Peer-to-peer networking library" -version = "0.21.1" +version = "0.22.0" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" @@ -68,7 +68,7 @@ libp2p-gossipsub = { version = "0.20.0", path = "./protocols/gossipsub", optiona libp2p-identify = { version = "0.20.0", path = "protocols/identify", optional = true } libp2p-kad = { version = "0.21.0", path = "protocols/kad", optional = true } libp2p-mplex = { version = "0.20.0", path = "muxers/mplex", optional = true } -libp2p-noise = { version = "0.20.0", path = "protocols/noise", optional = true } +libp2p-noise = { version = "0.21.0", path = "protocols/noise", optional = true } libp2p-ping = { version = "0.20.0", path = "protocols/ping", optional = true } libp2p-plaintext = { version = "0.20.0", path = "protocols/plaintext", optional = true } libp2p-pnet = { version = "0.19.1", path = "protocols/pnet", optional = true } diff --git a/protocols/noise/CHANGELOG.md b/protocols/noise/CHANGELOG.md index 3e1511fb..6c19f01c 100644 --- a/protocols/noise/CHANGELOG.md +++ b/protocols/noise/CHANGELOG.md @@ -1,3 +1,14 @@ +# 0.21.0 [2020-07-17] + +**NOTE**: For a smooth upgrade path from `0.20` to `> 0.21` +on an existing deployment, this version must not be skipped! + +- Add support for reading handshake protobuf frames without +length prefixes in preparation for no longer sending them. +See [issue 1631](https://github.com/libp2p/rust-libp2p/issues/1631). + +- Update the `snow` dependency to the latest patch version. + # 0.20.0 [2020-07-01] - Updated dependencies. diff --git a/protocols/noise/Cargo.toml b/protocols/noise/Cargo.toml index 918ed631..7f513482 100644 --- a/protocols/noise/Cargo.toml +++ b/protocols/noise/Cargo.toml @@ -1,13 +1,14 @@ [package] name = "libp2p-noise" description = "Cryptographic handshake protocol using the noise framework." -version = "0.20.0" +version = "0.21.0" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" edition = "2018" [dependencies] +bytes = "0.5" curve25519-dalek = "2.0.0" futures = "0.3.1" lazy_static = "1.2" @@ -21,10 +22,10 @@ x25519-dalek = "0.6.0" zeroize = "1" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -snow = { version = "0.7.0", features = ["ring-resolver"], default-features = false } +snow = { version = "0.7.1", features = ["ring-resolver"], default-features = false } [target.'cfg(target_arch = "wasm32")'.dependencies] -snow = { version = "0.7.0", features = ["default-resolver"], default-features = false } +snow = { version = "0.7.1", features = ["default-resolver"], default-features = false } [dev-dependencies] env_logger = "0.7.1" diff --git a/protocols/noise/src/io.rs b/protocols/noise/src/io.rs index d3900a5c..751280a6 100644 --- a/protocols/noise/src/io.rs +++ b/protocols/noise/src/io.rs @@ -20,378 +20,118 @@ //! Noise protocol I/O. +mod framed; pub mod handshake; +use bytes::Bytes; +use framed::{MAX_FRAME_LEN, NoiseFramed}; use futures::ready; use futures::prelude::*; -use log::{debug, trace}; -use snow; -use std::{cmp::min, fmt, io, pin::Pin, ops::DerefMut, task::{Context, Poll}}; - -/// Max. size of a noise package. -const MAX_NOISE_PKG_LEN: usize = 65535; -/// Extra space given to the encryption buffer to hold key material. -const EXTRA_ENCRYPT_SPACE: usize = 1024; -/// Max. output buffer size before forcing a flush. -const MAX_WRITE_BUF_LEN: usize = MAX_NOISE_PKG_LEN - EXTRA_ENCRYPT_SPACE; - -static_assertions::const_assert! { - MAX_WRITE_BUF_LEN + EXTRA_ENCRYPT_SPACE <= MAX_NOISE_PKG_LEN -} - -/// A passthrough enum for the two kinds of state machines in `snow` -pub(crate) enum SnowState { - Transport(snow::TransportState), - Handshake(snow::HandshakeState) -} - -impl SnowState { - pub fn read_message(&mut self, message: &[u8], payload: &mut [u8]) -> Result { - match self { - SnowState::Handshake(session) => session.read_message(message, payload), - SnowState::Transport(session) => session.read_message(message, payload), - } - } - - pub fn write_message(&mut self, message: &[u8], payload: &mut [u8]) -> Result { - match self { - SnowState::Handshake(session) => session.write_message(message, payload), - SnowState::Transport(session) => session.write_message(message, payload), - } - } - - pub fn get_remote_static(&self) -> Option<&[u8]> { - match self { - SnowState::Handshake(session) => session.get_remote_static(), - SnowState::Transport(session) => session.get_remote_static(), - } - } - - pub fn into_transport_mode(self) -> Result { - match self { - SnowState::Handshake(session) => session.into_transport_mode(), - SnowState::Transport(_) => Err(snow::Error::State(snow::error::StateProblem::HandshakeAlreadyFinished)), - } - } -} +use log::trace; +use std::{cmp::min, fmt, io, pin::Pin, task::{Context, Poll}}; /// A noise session to a remote. /// /// `T` is the type of the underlying I/O resource. pub struct NoiseOutput { - io: T, - session: SnowState, - read_state: ReadState, - write_state: WriteState, - read_buffer: Vec, - write_buffer: Vec, - decrypt_buffer: Vec, - encrypt_buffer: Vec + io: NoiseFramed, + recv_buffer: Bytes, + recv_offset: usize, + send_buffer: Vec, + send_offset: usize, } impl fmt::Debug for NoiseOutput { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("NoiseOutput") - .field("read_state", &self.read_state) - .field("write_state", &self.write_state) + .field("io", &self.io) .finish() } } impl NoiseOutput { - fn new(io: T, session: SnowState) -> Self { + fn new(io: NoiseFramed) -> Self { NoiseOutput { io, - session, - read_state: ReadState::Init, - write_state: WriteState::Init, - read_buffer: Vec::new(), - write_buffer: Vec::new(), - decrypt_buffer: Vec::new(), - encrypt_buffer: Vec::new() + recv_buffer: Bytes::new(), + recv_offset: 0, + send_buffer: Vec::new(), + send_offset: 0, } } } -/// The various states of reading a noise session transitions through. -#[derive(Debug)] -enum ReadState { - /// initial state - Init, - /// read frame length - ReadLen { buf: [u8; 2], off: usize }, - /// read encrypted frame data - ReadData { len: usize, off: usize }, - /// copy decrypted frame data - CopyData { len: usize, off: usize }, - /// end of file has been reached (terminal state) - /// The associated result signals if the EOF was unexpected or not. - Eof(Result<(), ()>), - /// decryption error (terminal state) - DecErr -} - -/// The various states of writing a noise session transitions through. -#[derive(Debug)] -enum WriteState { - /// initial state - Init, - /// accumulate write data - BufferData { off: usize }, - /// write frame length - WriteLen { len: usize, buf: [u8; 2], off: usize }, - /// write out encrypted data - WriteData { len: usize, off: usize }, - /// end of file has been reached (terminal state) - Eof, - /// encryption error (terminal state) - EncErr -} - impl AsyncRead for NoiseOutput { fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll> { - let mut this = self.deref_mut(); loop { - trace!("read state: {:?}", this.read_state); - match this.read_state { - ReadState::Init => { - this.read_state = ReadState::ReadLen { buf: [0, 0], off: 0 }; + let len = self.recv_buffer.len(); + let off = self.recv_offset; + if len > 0 { + let n = min(len - off, buf.len()); + buf[.. n].copy_from_slice(&self.recv_buffer[off .. off + n]); + trace!("read: copied {}/{} bytes", off + n, len); + self.recv_offset += n; + if len == self.recv_offset { + trace!("read: frame consumed"); + // Drop the existing view so `NoiseFramed` can reuse + // the buffer when polling for the next frame below. + self.recv_buffer = Bytes::new(); } - ReadState::ReadLen { mut buf, mut off } => { - let n = match read_frame_len(&mut this.io, cx, &mut buf, &mut off) { - Poll::Ready(Ok(Some(n))) => n, - Poll::Ready(Ok(None)) => { - trace!("read: eof"); - this.read_state = ReadState::Eof(Ok(())); - return Poll::Ready(Ok(0)) - } - Poll::Ready(Err(e)) => { - return Poll::Ready(Err(e)) - } - Poll::Pending => { - this.read_state = ReadState::ReadLen { buf, off }; - return Poll::Pending; - } - }; - trace!("read: next frame len = {}", n); - if n == 0 { - trace!("read: empty frame"); - this.read_state = ReadState::Init; - continue - } - this.read_buffer.resize(usize::from(n), 0u8); - this.read_state = ReadState::ReadData { len: usize::from(n), off: 0 } + return Poll::Ready(Ok(n)) + } + + match Pin::new(&mut self.io).poll_next(cx) { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => return Poll::Ready(Ok(0)), + Poll::Ready(Some(Err(e))) => return Poll::Ready(Err(e)), + Poll::Ready(Some(Ok(frame))) => { + self.recv_buffer = frame; + self.recv_offset = 0; } - ReadState::ReadData { len, ref mut off } => { - let n = { - let f = Pin::new(&mut this.io).poll_read(cx, &mut this.read_buffer[*off .. len]); - match ready!(f) { - Ok(n) => n, - Err(e) => return Poll::Ready(Err(e)), - } - }; - trace!("read: read {}/{} bytes", *off + n, len); - if n == 0 { - trace!("read: eof"); - this.read_state = ReadState::Eof(Err(())); - return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())) - } - *off += n; - if len == *off { - trace!("read: decrypting {} bytes", len); - this.decrypt_buffer.resize(len, 0u8); - if let Ok(n) = this.session.read_message(&this.read_buffer, &mut this.decrypt_buffer) { - trace!("read: payload len = {} bytes", n); - this.read_state = ReadState::CopyData { len: n, off: 0 } - } else { - debug!("decryption error"); - this.read_state = ReadState::DecErr; - return Poll::Ready(Err(io::ErrorKind::InvalidData.into())) - } - } - } - ReadState::CopyData { len, ref mut off } => { - let n = min(len - *off, buf.len()); - buf[.. n].copy_from_slice(&this.decrypt_buffer[*off .. *off + n]); - trace!("read: copied {}/{} bytes", *off + n, len); - *off += n; - if len == *off { - this.read_state = ReadState::ReadLen { buf: [0, 0], off: 0 }; - } - return Poll::Ready(Ok(n)) - } - ReadState::Eof(Ok(())) => { - trace!("read: eof"); - return Poll::Ready(Ok(0)) - } - ReadState::Eof(Err(())) => { - trace!("read: eof (unexpected)"); - return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())) - } - ReadState::DecErr => return Poll::Ready(Err(io::ErrorKind::InvalidData.into())) } } } } impl AsyncWrite for NoiseOutput { - fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll> { - let mut this = self.deref_mut(); - loop { - trace!("write state: {:?}", this.write_state); - match this.write_state { - WriteState::Init => { - this.write_state = WriteState::BufferData { off: 0 } - } - WriteState::BufferData { ref mut off } => { - let n = min(MAX_WRITE_BUF_LEN, off.saturating_add(buf.len())); - this.write_buffer.resize(n, 0u8); - let n = min(MAX_WRITE_BUF_LEN - *off, buf.len()); - this.write_buffer[*off .. *off + n].copy_from_slice(&buf[.. n]); - trace!("write: buffered {} bytes", *off + n); - *off += n; - if *off == MAX_WRITE_BUF_LEN { - trace!("write: encrypting {} bytes", *off); - this.encrypt_buffer.resize(MAX_WRITE_BUF_LEN + EXTRA_ENCRYPT_SPACE, 0u8); - match this.session.write_message(&this.write_buffer, &mut this.encrypt_buffer) { - Ok(n) => { - trace!("write: cipher text len = {} bytes", n); - this.write_state = WriteState::WriteLen { - len: n, - buf: u16::to_be_bytes(n as u16), - off: 0 - } - } - Err(e) => { - debug!("encryption error: {:?}", e); - this.write_state = WriteState::EncErr; - return Poll::Ready(Err(io::ErrorKind::InvalidData.into())) - } - } - } - return Poll::Ready(Ok(n)) - } - WriteState::WriteLen { len, mut buf, mut off } => { - trace!("write: writing len ({}, {:?}, {}/2)", len, buf, off); - match write_frame_len(&mut this.io, cx, &mut buf, &mut off) { - Poll::Ready(Ok(true)) => (), - Poll::Ready(Ok(false)) => { - trace!("write: eof"); - this.write_state = WriteState::Eof; - return Poll::Ready(Err(io::ErrorKind::WriteZero.into())) - } - Poll::Ready(Err(e)) => { - return Poll::Ready(Err(e)) - } - Poll::Pending => { - this.write_state = WriteState::WriteLen{ len, buf, off }; + fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll> { + let this = Pin::into_inner(self); + let mut io = Pin::new(&mut this.io); + let frame_buf = &mut this.send_buffer; - return Poll::Pending - } - } - this.write_state = WriteState::WriteData { len, off: 0 } - } - WriteState::WriteData { len, ref mut off } => { - let n = { - let f = Pin::new(&mut this.io).poll_write(cx, &this.encrypt_buffer[*off .. len]); - match ready!(f) { - Ok(n) => n, - Err(e) => return Poll::Ready(Err(e)) - } - }; - trace!("write: wrote {}/{} bytes", *off + n, len); - if n == 0 { - trace!("write: eof"); - this.write_state = WriteState::Eof; - return Poll::Ready(Err(io::ErrorKind::WriteZero.into())) - } - *off += n; - if len == *off { - trace!("write: finished writing {} bytes", len); - this.write_state = WriteState::Init - } - } - WriteState::Eof => { - trace!("write: eof"); - return Poll::Ready(Err(io::ErrorKind::WriteZero.into())) - } - WriteState::EncErr => return Poll::Ready(Err(io::ErrorKind::InvalidData.into())) - } + // The MAX_FRAME_LEN is the maximum buffer size before a frame must be sent. + if this.send_offset == MAX_FRAME_LEN { + trace!("write: sending {} bytes", MAX_FRAME_LEN); + ready!(io.as_mut().poll_ready(cx))?; + io.as_mut().start_send(&frame_buf)?; + this.send_offset = 0; } + + let off = this.send_offset; + let n = min(MAX_FRAME_LEN, off.saturating_add(buf.len())); + this.send_buffer.resize(n, 0u8); + let n = min(MAX_FRAME_LEN - off, buf.len()); + this.send_buffer[off .. off + n].copy_from_slice(&buf[.. n]); + this.send_offset += n; + trace!("write: buffered {} bytes", this.send_offset); + + return Poll::Ready(Ok(n)) } - fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { - let mut this = self.deref_mut(); - loop { - match this.write_state { - WriteState::Init => { - return Pin::new(&mut this.io).poll_flush(cx) - } - WriteState::BufferData { off } => { - trace!("flush: encrypting {} bytes", off); - this.encrypt_buffer.resize(off + EXTRA_ENCRYPT_SPACE, 0u8); - match this.session.write_message(&this.write_buffer[.. off], &mut this.encrypt_buffer) { - Ok(n) => { - trace!("flush: cipher text len = {} bytes", n); - this.write_state = WriteState::WriteLen { - len: n, - buf: u16::to_be_bytes(n as u16), - off: 0 - } - } - Err(e) => { - debug!("encryption error: {:?}", e); - this.write_state = WriteState::EncErr; - return Poll::Ready(Err(io::ErrorKind::InvalidData.into())) - } - } - } - WriteState::WriteLen { len, mut buf, mut off } => { - trace!("flush: writing len ({}, {:?}, {}/2)", len, buf, off); - match write_frame_len(&mut this.io, cx, &mut buf, &mut off) { - Poll::Ready(Ok(true)) => (), - Poll::Ready(Ok(false)) => { - trace!("write: eof"); - this.write_state = WriteState::Eof; - return Poll::Ready(Err(io::ErrorKind::WriteZero.into())) - } - Poll::Ready(Err(e)) => { - return Poll::Ready(Err(e)) - } - Poll::Pending => { - this.write_state = WriteState::WriteLen { len, buf, off }; - return Poll::Pending - } - } - this.write_state = WriteState::WriteData { len, off: 0 } - } - WriteState::WriteData { len, ref mut off } => { - let n = { - let f = Pin::new(&mut this.io).poll_write(cx, &this.encrypt_buffer[*off .. len]); - match ready!(f) { - Ok(n) => n, - Err(e) => return Poll::Ready(Err(e)), - } - }; - trace!("flush: wrote {}/{} bytes", *off + n, len); - if n == 0 { - trace!("flush: eof"); - this.write_state = WriteState::Eof; - return Poll::Ready(Err(io::ErrorKind::WriteZero.into())) - } - *off += n; - if len == *off { - trace!("flush: finished writing {} bytes", len); - this.write_state = WriteState::Init; - } - } - WriteState::Eof => { - trace!("flush: eof"); - return Poll::Ready(Err(io::ErrorKind::WriteZero.into())) - } - WriteState::EncErr => return Poll::Ready(Err(io::ErrorKind::InvalidData.into())) - } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + let this = Pin::into_inner(self); + let mut io = Pin::new(&mut this.io); + let frame_buf = &mut this.send_buffer; + + // Check if there is still one more frame to send. + if this.send_offset > 0 { + ready!(io.as_mut().poll_ready(cx))?; + trace!("flush: sending {} bytes", this.send_offset); + io.as_mut().start_send(&frame_buf)?; + this.send_offset = 0; } + + io.as_mut().poll_flush(cx) } fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll>{ @@ -399,69 +139,3 @@ impl AsyncWrite for NoiseOutput { Pin::new(&mut self.io).poll_close(cx) } } - -/// Read 2 bytes as frame length from the given source into the given buffer. -/// -/// Panics if `off >= 2`. -/// -/// When [`Poll::Pending`] is returned, the given buffer and offset -/// may have been updated (i.e. a byte may have been read) and must be preserved -/// for the next invocation. -/// -/// Returns `None` if EOF has been encountered. -fn read_frame_len( - mut io: &mut R, - cx: &mut Context<'_>, - buf: &mut [u8; 2], - off: &mut usize, -) -> Poll>> { - loop { - match ready!(Pin::new(&mut io).poll_read(cx, &mut buf[*off ..])) { - Ok(n) => { - if n == 0 { - return Poll::Ready(Ok(None)); - } - *off += n; - if *off == 2 { - return Poll::Ready(Ok(Some(u16::from_be_bytes(*buf)))); - } - }, - Err(e) => { - return Poll::Ready(Err(e)); - }, - } - } -} - -/// Write 2 bytes as frame length from the given buffer into the given sink. -/// -/// Panics if `off >= 2`. -/// -/// When [`Poll::Pending`] is returned, the given offset -/// may have been updated (i.e. a byte may have been written) and must -/// be preserved for the next invocation. -/// -/// Returns `false` if EOF has been encountered. -fn write_frame_len( - mut io: &mut W, - cx: &mut Context<'_>, - buf: &[u8; 2], - off: &mut usize, -) -> Poll> { - loop { - match ready!(Pin::new(&mut io).poll_write(cx, &buf[*off ..])) { - Ok(n) => { - if n == 0 { - return Poll::Ready(Ok(false)) - } - *off += n; - if *off == 2 { - return Poll::Ready(Ok(true)) - } - } - Err(e) => { - return Poll::Ready(Err(e)); - } - } - } -} diff --git a/protocols/noise/src/io/framed.rs b/protocols/noise/src/io/framed.rs new file mode 100644 index 00000000..ce0a8269 --- /dev/null +++ b/protocols/noise/src/io/framed.rs @@ -0,0 +1,439 @@ +// Copyright 2020 Parity Technologies (UK) Ltd. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. + +//! This module provides a `Sink` and `Stream` for length-delimited +//! Noise protocol messages in form of [`NoiseFramed`]. + +use bytes::{Bytes, BytesMut}; +use crate::{NoiseError, Protocol, PublicKey}; +use crate::io::NoiseOutput; +use futures::ready; +use futures::prelude::*; +use log::{debug, trace}; +use snow; +use std::{fmt, io, pin::Pin, task::{Context, Poll}}; + +/// Max. size of a noise message. +const MAX_NOISE_MSG_LEN: usize = 65535; +/// Space given to the encryption buffer to hold key material. +const EXTRA_ENCRYPT_SPACE: usize = 1024; +/// Max. length for Noise protocol message payloads. +pub const MAX_FRAME_LEN: usize = MAX_NOISE_MSG_LEN - EXTRA_ENCRYPT_SPACE; + +static_assertions::const_assert! { + MAX_FRAME_LEN + EXTRA_ENCRYPT_SPACE <= MAX_NOISE_MSG_LEN +} + +/// A `NoiseFramed` is a `Sink` and `Stream` for length-delimited +/// Noise protocol messages. +/// +/// `T` is the type of the underlying I/O resource and `S` the +/// type of the Noise session state. +pub struct NoiseFramed { + io: T, + session: S, + read_state: ReadState, + write_state: WriteState, + read_buffer: Vec, + write_buffer: Vec, + decrypt_buffer: BytesMut, +} + +impl fmt::Debug for NoiseFramed { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("NoiseFramed") + .field("read_state", &self.read_state) + .field("write_state", &self.write_state) + .finish() + } +} + +impl NoiseFramed { + /// Creates a nwe `NoiseFramed` for beginning a Noise protocol handshake. + pub fn new(io: T, state: snow::HandshakeState) -> Self { + NoiseFramed { + io, + session: state, + read_state: ReadState::Ready, + write_state: WriteState::Ready, + read_buffer: Vec::new(), + write_buffer: Vec::new(), + decrypt_buffer: BytesMut::new(), + } + } + + /// Converts the `NoiseFramed` into a `NoiseOutput` encrypted data stream + /// once the handshake is complete, including the static DH [`PublicKey`] + /// of the remote, if received. + /// + /// If the underlying Noise protocol session state does not permit + /// transitioning to transport mode because the handshake is incomplete, + /// an error is returned. Similarly if the remote's static DH key, if + /// present, cannot be parsed. + pub fn into_transport(self) -> Result<(Option>, NoiseOutput), NoiseError> + where + C: Protocol + AsRef<[u8]> + { + let dh_remote_pubkey = match self.session.get_remote_static() { + None => None, + Some(k) => match C::public_from_bytes(k) { + Err(e) => return Err(e), + Ok(dh_pk) => Some(dh_pk) + } + }; + match self.session.into_transport_mode() { + Err(e) => Err(e.into()), + Ok(s) => { + let io = NoiseFramed { + session: s, + io: self.io, + read_state: ReadState::Ready, + write_state: WriteState::Ready, + read_buffer: self.read_buffer, + write_buffer: self.write_buffer, + decrypt_buffer: self.decrypt_buffer, + }; + Ok((dh_remote_pubkey, NoiseOutput::new(io))) + } + } + } +} + +/// The states for reading Noise protocol frames. +#[derive(Debug)] +enum ReadState { + /// Ready to read another frame. + Ready, + /// Reading frame length. + ReadLen { buf: [u8; 2], off: usize }, + /// Reading frame data. + ReadData { len: usize, off: usize }, + /// EOF has been reached (terminal state). + /// + /// The associated result signals if the EOF was unexpected or not. + Eof(Result<(), ()>), + /// A decryption error occurred (terminal state). + DecErr +} + +/// The states for writing Noise protocol frames. +#[derive(Debug)] +enum WriteState { + /// Ready to write another frame. + Ready, + /// Writing the frame length. + WriteLen { len: usize, buf: [u8; 2], off: usize }, + /// Writing the frame data. + WriteData { len: usize, off: usize }, + /// EOF has been reached unexpectedly (terminal state). + Eof, + /// An encryption error occurred (terminal state). + EncErr +} + +impl WriteState { + fn is_ready(&self) -> bool { + if let WriteState::Ready = self { + return true + } + false + } +} + +impl futures::stream::Stream for NoiseFramed +where + T: AsyncRead + Unpin, + S: SessionState + Unpin +{ + type Item = io::Result; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + let mut this = Pin::into_inner(self); + loop { + trace!("read state: {:?}", this.read_state); + match this.read_state { + ReadState::Ready => { + this.read_state = ReadState::ReadLen { buf: [0, 0], off: 0 }; + } + ReadState::ReadLen { mut buf, mut off } => { + let n = match read_frame_len(&mut this.io, cx, &mut buf, &mut off) { + Poll::Ready(Ok(Some(n))) => n, + Poll::Ready(Ok(None)) => { + trace!("read: eof"); + this.read_state = ReadState::Eof(Ok(())); + return Poll::Ready(None) + } + Poll::Ready(Err(e)) => { + return Poll::Ready(Some(Err(e))) + } + Poll::Pending => { + this.read_state = ReadState::ReadLen { buf, off }; + return Poll::Pending; + } + }; + trace!("read: frame len = {}", n); + if n == 0 { + trace!("read: empty frame"); + this.read_state = ReadState::Ready; + continue + } + this.read_buffer.resize(usize::from(n), 0u8); + this.read_state = ReadState::ReadData { len: usize::from(n), off: 0 } + } + ReadState::ReadData { len, ref mut off } => { + let n = { + let f = Pin::new(&mut this.io).poll_read(cx, &mut this.read_buffer[*off .. len]); + match ready!(f) { + Ok(n) => n, + Err(e) => return Poll::Ready(Some(Err(e))), + } + }; + trace!("read: {}/{} bytes", *off + n, len); + if n == 0 { + trace!("read: eof"); + this.read_state = ReadState::Eof(Err(())); + return Poll::Ready(Some(Err(io::ErrorKind::UnexpectedEof.into()))) + } + *off += n; + if len == *off { + trace!("read: decrypting {} bytes", len); + this.decrypt_buffer.resize(len, 0); + if let Ok(n) = this.session.read_message(&this.read_buffer, &mut this.decrypt_buffer) { + this.decrypt_buffer.truncate(n); + trace!("read: payload len = {} bytes", n); + this.read_state = ReadState::Ready; + // Return an immutable view into the current buffer. + // If the view is dropped before the next frame is + // read, the `BytesMut` will reuse the same buffer + // for the next frame. + let view = this.decrypt_buffer.split().freeze(); + return Poll::Ready(Some(Ok(view))) + } else { + debug!("read: decryption error"); + this.read_state = ReadState::DecErr; + return Poll::Ready(Some(Err(io::ErrorKind::InvalidData.into()))) + } + } + } + ReadState::Eof(Ok(())) => { + trace!("read: eof"); + return Poll::Ready(None) + } + ReadState::Eof(Err(())) => { + trace!("read: eof (unexpected)"); + return Poll::Ready(Some(Err(io::ErrorKind::UnexpectedEof.into()))) + } + ReadState::DecErr => return Poll::Ready(Some(Err(io::ErrorKind::InvalidData.into()))) + } + } + } +} + +impl futures::sink::Sink<&Vec> for NoiseFramed +where + T: AsyncWrite + Unpin, + S: SessionState + Unpin +{ + type Error = io::Error; + + fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + let mut this = Pin::into_inner(self); + loop { + trace!("write state {:?}", this.write_state); + match this.write_state { + WriteState::Ready => { + return Poll::Ready(Ok(())); + } + WriteState::WriteLen { len, mut buf, mut off } => { + trace!("write: frame len ({}, {:?}, {}/2)", len, buf, off); + match write_frame_len(&mut this.io, cx, &mut buf, &mut off) { + Poll::Ready(Ok(true)) => (), + Poll::Ready(Ok(false)) => { + trace!("write: eof"); + this.write_state = WriteState::Eof; + return Poll::Ready(Err(io::ErrorKind::WriteZero.into())) + } + Poll::Ready(Err(e)) => { + return Poll::Ready(Err(e)) + } + Poll::Pending => { + this.write_state = WriteState::WriteLen { len, buf, off }; + return Poll::Pending + } + } + this.write_state = WriteState::WriteData { len, off: 0 } + } + WriteState::WriteData { len, ref mut off } => { + let n = { + let f = Pin::new(&mut this.io).poll_write(cx, &this.write_buffer[*off .. len]); + match ready!(f) { + Ok(n) => n, + Err(e) => return Poll::Ready(Err(e)), + } + }; + if n == 0 { + trace!("write: eof"); + this.write_state = WriteState::Eof; + return Poll::Ready(Err(io::ErrorKind::WriteZero.into())) + } + *off += n; + trace!("write: {}/{} bytes written", *off, len); + if len == *off { + trace!("write: finished with {} bytes", len); + this.write_state = WriteState::Ready; + } + } + WriteState::Eof => { + trace!("write: eof"); + return Poll::Ready(Err(io::ErrorKind::WriteZero.into())) + } + WriteState::EncErr => return Poll::Ready(Err(io::ErrorKind::InvalidData.into())) + } + } + } + + fn start_send(self: Pin<&mut Self>, frame: &Vec) -> Result<(), Self::Error> { + assert!(frame.len() <= MAX_FRAME_LEN); + let mut this = Pin::into_inner(self); + assert!(this.write_state.is_ready()); + + this.write_buffer.resize(frame.len() + EXTRA_ENCRYPT_SPACE, 0u8); + match this.session.write_message(frame, &mut this.write_buffer[..]) { + Ok(n) => { + trace!("write: cipher text len = {} bytes", n); + this.write_buffer.truncate(n); + this.write_state = WriteState::WriteLen { + len: n, + buf: u16::to_be_bytes(n as u16), + off: 0 + }; + return Ok(()) + } + Err(e) => { + log::error!("encryption error: {:?}", e); + this.write_state = WriteState::EncErr; + return Err(io::ErrorKind::InvalidData.into()) + } + } + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + ready!(self.as_mut().poll_ready(cx))?; + Pin::new(&mut self.io).poll_flush(cx) + } + + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + ready!(self.as_mut().poll_flush(cx))?; + Pin::new(&mut self.io).poll_close(cx) + } +} + +/// A stateful context in which Noise protocol messages can be read and written. +pub trait SessionState { + fn read_message(&mut self, msg: &[u8], buf: &mut [u8]) -> Result; + fn write_message(&mut self, msg: &[u8], buf: &mut [u8]) -> Result; +} + +impl SessionState for snow::HandshakeState { + fn read_message(&mut self, msg: &[u8], buf: &mut [u8]) -> Result { + self.read_message(msg, buf) + } + + fn write_message(&mut self, msg: &[u8], buf: &mut [u8]) -> Result { + self.write_message(msg, buf) + } +} + +impl SessionState for snow::TransportState { + fn read_message(&mut self, msg: &[u8], buf: &mut [u8]) -> Result { + self.read_message(msg, buf) + } + + fn write_message(&mut self, msg: &[u8], buf: &mut [u8]) -> Result { + self.write_message(msg, buf) + } +} + +/// Read 2 bytes as frame length from the given source into the given buffer. +/// +/// Panics if `off >= 2`. +/// +/// When [`Poll::Pending`] is returned, the given buffer and offset +/// may have been updated (i.e. a byte may have been read) and must be preserved +/// for the next invocation. +/// +/// Returns `None` if EOF has been encountered. +fn read_frame_len( + mut io: &mut R, + cx: &mut Context<'_>, + buf: &mut [u8; 2], + off: &mut usize, +) -> Poll>> { + loop { + match ready!(Pin::new(&mut io).poll_read(cx, &mut buf[*off ..])) { + Ok(n) => { + if n == 0 { + return Poll::Ready(Ok(None)); + } + *off += n; + if *off == 2 { + return Poll::Ready(Ok(Some(u16::from_be_bytes(*buf)))); + } + }, + Err(e) => { + return Poll::Ready(Err(e)); + }, + } + } +} + +/// Write 2 bytes as frame length from the given buffer into the given sink. +/// +/// Panics if `off >= 2`. +/// +/// When [`Poll::Pending`] is returned, the given offset +/// may have been updated (i.e. a byte may have been written) and must +/// be preserved for the next invocation. +/// +/// Returns `false` if EOF has been encountered. +fn write_frame_len( + mut io: &mut W, + cx: &mut Context<'_>, + buf: &[u8; 2], + off: &mut usize, +) -> Poll> { + loop { + match ready!(Pin::new(&mut io).poll_write(cx, &buf[*off ..])) { + Ok(n) => { + if n == 0 { + return Poll::Ready(Ok(false)) + } + *off += n; + if *off == 2 { + return Poll::Ready(Ok(true)) + } + } + Err(e) => { + return Poll::Ready(Err(e)); + } + } + } +} + diff --git a/protocols/noise/src/io/handshake.rs b/protocols/noise/src/io/handshake.rs index 047951ed..affd38a3 100644 --- a/protocols/noise/src/io/handshake.rs +++ b/protocols/noise/src/io/handshake.rs @@ -24,16 +24,15 @@ mod payload_proto { include!(concat!(env!("OUT_DIR"), "/payload.proto.rs")); } +use bytes::Bytes; use crate::error::NoiseError; use crate::protocol::{Protocol, PublicKey, KeypairIdentity}; -use crate::io::SnowState; +use crate::io::{NoiseOutput, framed::NoiseFramed}; use libp2p_core::identity; use futures::prelude::*; use futures::task; -use futures::io::AsyncReadExt; use prost::Message; -use std::{pin::Pin, task::Context}; -use super::NoiseOutput; +use std::{io, pin::Pin, task::Context}; /// The identity of the remote established during a handshake. pub enum RemoteIdentity { @@ -254,7 +253,7 @@ where /// Handshake state. struct State { /// The underlying I/O resource. - io: NoiseOutput, + io: NoiseFramed, /// The associated public identity of the local node's static DH keypair, /// which can be sent to the remote as part of an authenticated handshake. identity: KeypairIdentity, @@ -287,7 +286,7 @@ impl State { session.map(|s| State { identity, - io: NoiseOutput::new(io, SnowState::Handshake(s)), + io: NoiseFramed::new(io, s), dh_remote_pubkey_sig: None, id_remote_pubkey, send_identity @@ -304,42 +303,48 @@ impl State where C: Protocol + AsRef<[u8]> { - let dh_remote_pubkey = match self.io.session.get_remote_static() { - None => None, - Some(k) => match C::public_from_bytes(k) { - Err(e) => return Err(e), - Ok(dh_pk) => Some(dh_pk) + let (pubkey, io) = self.io.into_transport()?; + let remote = match (self.id_remote_pubkey, pubkey) { + (_, None) => RemoteIdentity::Unknown, + (None, Some(dh_pk)) => RemoteIdentity::StaticDhKey(dh_pk), + (Some(id_pk), Some(dh_pk)) => { + if C::verify(&id_pk, &dh_pk, &self.dh_remote_pubkey_sig) { + RemoteIdentity::IdentityKey(id_pk) + } else { + return Err(NoiseError::InvalidKey) + } } }; - match self.io.session.into_transport_mode() { - Err(e) => Err(e.into()), - Ok(s) => { - let remote = match (self.id_remote_pubkey, dh_remote_pubkey) { - (_, None) => RemoteIdentity::Unknown, - (None, Some(dh_pk)) => RemoteIdentity::StaticDhKey(dh_pk), - (Some(id_pk), Some(dh_pk)) => { - if C::verify(&id_pk, &dh_pk, &self.dh_remote_pubkey_sig) { - RemoteIdentity::IdentityKey(id_pk) - } else { - return Err(NoiseError::InvalidKey) - } - } - }; - Ok((remote, NoiseOutput { session: SnowState::Transport(s), .. self.io })) - } - } + Ok((remote, io)) } } ////////////////////////////////////////////////////////////////////////////// // Handshake Message Futures +/// A future for receiving a Noise handshake message. +async fn recv(state: &mut State) -> Result +where + T: AsyncRead + Unpin +{ + match state.io.next().await { + None => Err(io::Error::new(io::ErrorKind::UnexpectedEof, "eof").into()), + Some(Err(e)) => Err(e.into()), + Some(Ok(m)) => Ok(m), + } +} + /// A future for receiving a Noise handshake message with an empty payload. async fn recv_empty(state: &mut State) -> Result<(), NoiseError> where T: AsyncRead + Unpin { - state.io.read(&mut []).await?; + let msg = recv(state).await?; + if !msg.is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Unexpected handshake payload.").into()) + } Ok(()) } @@ -348,8 +353,7 @@ async fn send_empty(state: &mut State) -> Result<(), NoiseError> where T: AsyncWrite + Unpin { - state.io.write(&[]).await?; - state.io.flush().await?; + state.io.send(&Vec::new()).await?; Ok(()) } @@ -359,13 +363,42 @@ async fn recv_identity(state: &mut State) -> Result<(), NoiseError> where T: AsyncRead + Unpin, { - let mut len_buf = [0,0]; - state.io.read_exact(&mut len_buf).await?; - let len = u16::from_be_bytes(len_buf) as usize; + let msg = recv(state).await?; - let mut payload_buf = vec![0; len]; - state.io.read_exact(&mut payload_buf).await?; - let pb = payload_proto::NoiseHandshakePayload::decode(&payload_buf[..])?; + // NOTE: We first try to decode the entire frame as a protobuf message, + // as required by the libp2p-noise spec. As long as the frame length + // is less than 256 bytes, which is the case for all protobuf payloads + // not containing RSA keys, there is no room for misinterpretation, + // since if a two-bytes length prefix is present the first byte will + // be 0, which is always an unexpected protobuf tag value because the + // fields in the .proto file start with 1 and decoding thus expects + // a non-zero first byte. We will therefore always correctly fall back to + // the legacy protobuf parsing in these cases (again, not considering + // RSA keys, for which there may be a probabilistically very small chance + // of misinterpretation). + // + // This is only temporary! Once a release is made that supports + // decoding without a length prefix, a follow-up release will + // change `send_identity` such that no length prefix is sent. + // In yet another release the fallback protobuf parsing can then + // be removed. + let pb = payload_proto::NoiseHandshakePayload::decode(&msg[..]) + .or_else(|e| { + if msg.len() > 2 { + let mut buf = [0, 0]; + buf.copy_from_slice(&msg[.. 2]); + // If there is a second length it must be 2 bytes shorter than the + // frame length, because each length is encoded as a `u16`. + if usize::from(u16::from_be_bytes(buf)) + 2 == msg.len() { + log::debug!("Attempting fallback legacy protobuf decoding."); + payload_proto::NoiseHandshakePayload::decode(&msg[2 ..]) + } else { + Err(e) + } + } else { + Err(e) + } + })?; if !pb.identity_key.is_empty() { let pk = identity::PublicKey::from_protobuf_encoding(&pb.identity_key) @@ -377,6 +410,7 @@ where } state.id_remote_pubkey = Some(pk); } + if !pb.identity_sig.is_empty() { state.dh_remote_pubkey_sig = Some(pb.identity_sig); } @@ -396,11 +430,11 @@ where if let Some(ref sig) = state.identity.signature { pb.identity_sig = sig.clone() } - let mut buf = Vec::with_capacity(pb.encoded_len()); - pb.encode(&mut buf).expect("Vec provides capacity as needed"); - let len = (buf.len() as u16).to_be_bytes(); - state.io.write_all(&len).await?; - state.io.write_all(&buf).await?; - state.io.flush().await?; + // NOTE: We temporarily need to continue sending the (legacy) length prefix + // for a short while to permit migration. + let mut msg = Vec::with_capacity(pb.encoded_len() + 2); + msg.extend_from_slice(&(pb.encoded_len() as u16).to_be_bytes()); + pb.encode(&mut msg).expect("Vec provides capacity as needed"); + state.io.send(&msg).await?; Ok(()) } From 8a08f72e84369958e9ee78ddb04cc0c9dcb7ef9d Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Mon, 27 Jul 2020 11:05:59 +0200 Subject: [PATCH 2/6] Refactor the bandwidth logging to be less magic (#1670) * Refactor the bandwidth logging to be less magic * Apply suggestions from code review Co-authored-by: Roman Borschel * Complete renaming. * Update changelog. Co-authored-by: Roman Borschel Co-authored-by: Roman S. Borschel --- CHANGELOG.md | 4 ++ Cargo.toml | 1 + src/bandwidth.rs | 155 +++++++++---------------------------------- src/transport_ext.rs | 10 +-- 4 files changed, 43 insertions(+), 127 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8be6676..d9aeb8b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,10 @@ - [`parity-multiaddr` CHANGELOG](misc/multiaddr/CHANGELOG.md) - [`libp2p-core-derive` CHANGELOG](misc/core-derive/CHANGELOG.md) +# Version 0.23.0 (2020-??-??) + +- Refactored bandwidth logging ([PR 1670](https://github.com/libp2p/rust-libp2p/pull/1670)). + # Version 0.22.0 (2020-07-17) **NOTE**: For a smooth upgrade path from `0.21` to `> 0.22` diff --git a/Cargo.toml b/Cargo.toml index ea73c741..6c1c6241 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,6 +58,7 @@ secp256k1 = ["libp2p-core/secp256k1", "libp2p-secio/secp256k1"] all-features = true [dependencies] +atomic = "0.4.6" bytes = "0.5" futures = "0.3.1" lazy_static = "1.2" diff --git a/src/bandwidth.rs b/src/bandwidth.rs index 33ec9897..ca067b4d 100644 --- a/src/bandwidth.rs +++ b/src/bandwidth.rs @@ -19,14 +19,15 @@ // DEALINGS IN THE SOFTWARE. use crate::{Multiaddr, core::{Transport, transport::{ListenerEvent, TransportError}}}; -use futures::{prelude::*, io::{IoSlice, IoSliceMut}, ready}; -use lazy_static::lazy_static; -use parking_lot::Mutex; -use smallvec::{smallvec, SmallVec}; -use std::{cmp, io, pin::Pin, sync::Arc, task::{Context, Poll}, time::Duration}; -use wasm_timer::Instant; -/// Wraps around a `Transport` and logs the bandwidth that goes through all the opened connections. +use atomic::Atomic; +use futures::{prelude::*, io::{IoSlice, IoSliceMut}, ready}; +use std::{ + convert::TryFrom as _, io, pin::Pin, sync::{atomic::Ordering, Arc}, task::{Context, Poll} +}; + +/// Wraps around a `Transport` and counts the number of bytes that go through all the opened +/// connections. #[derive(Clone)] pub struct BandwidthLogging { inner: TInner, @@ -34,16 +35,11 @@ pub struct BandwidthLogging { } impl BandwidthLogging { - /// Creates a new `BandwidthLogging` around the transport. - pub fn new(inner: TInner, period: Duration) -> (Self, Arc) { - let mut period_seconds = cmp::min(period.as_secs(), 86400) as u32; - if period.subsec_nanos() > 0 { - period_seconds += 1; - } - + /// Creates a new [`BandwidthLogging`] around the transport. + pub fn new(inner: TInner) -> (Self, Arc) { let sink = Arc::new(BandwidthSinks { - download: Mutex::new(BandwidthSink::new(period_seconds)), - upload: Mutex::new(BandwidthSink::new(period_seconds)), + inbound: Atomic::new(0), + outbound: Atomic::new(0), }); let trans = BandwidthLogging { @@ -134,21 +130,29 @@ impl Future for BandwidthFuture { } } -/// Allows obtaining the average bandwidth of the connections created from a `BandwidthLogging`. +/// Allows obtaining the average bandwidth of the connections created from a [`BandwidthLogging`]. pub struct BandwidthSinks { - download: Mutex, - upload: Mutex, + inbound: Atomic, + outbound: Atomic, } impl BandwidthSinks { - /// Returns the average number of bytes that have been downloaded in the period. - pub fn average_download_per_sec(&self) -> u64 { - self.download.lock().get() + /// Returns the total number of bytes that have been downloaded on all the connections spawned + /// through the [`BandwidthLogging`]. + /// + /// > **Note**: This method is by design subject to race conditions. The returned value should + /// > only ever be used for statistics purposes. + pub fn total_inbound(&self) -> u64 { + self.inbound.load(Ordering::Relaxed) } - /// Returns the average number of bytes that have been uploaded in the period. - pub fn average_upload_per_sec(&self) -> u64 { - self.upload.lock().get() + /// Returns the total number of bytes that have been uploaded on all the connections spawned + /// through the [`BandwidthLogging`]. + /// + /// > **Note**: This method is by design subject to race conditions. The returned value should + /// > only ever be used for statistics purposes. + pub fn total_outbound(&self) -> u64 { + self.outbound.load(Ordering::Relaxed) } } @@ -164,14 +168,14 @@ impl AsyncRead for BandwidthConnecLogging { fn poll_read(self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll> { let this = self.project(); let num_bytes = ready!(this.inner.poll_read(cx, buf))?; - this.sinks.download.lock().inject(num_bytes); + this.sinks.inbound.fetch_add(u64::try_from(num_bytes).unwrap_or(u64::max_value()), Ordering::Relaxed); Poll::Ready(Ok(num_bytes)) } fn poll_read_vectored(self: Pin<&mut Self>, cx: &mut Context, bufs: &mut [IoSliceMut]) -> Poll> { let this = self.project(); let num_bytes = ready!(this.inner.poll_read_vectored(cx, bufs))?; - this.sinks.download.lock().inject(num_bytes); + this.sinks.inbound.fetch_add(u64::try_from(num_bytes).unwrap_or(u64::max_value()), Ordering::Relaxed); Poll::Ready(Ok(num_bytes)) } } @@ -180,14 +184,14 @@ impl AsyncWrite for BandwidthConnecLogging { fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll> { let this = self.project(); let num_bytes = ready!(this.inner.poll_write(cx, buf))?; - this.sinks.upload.lock().inject(num_bytes); + this.sinks.outbound.fetch_add(u64::try_from(num_bytes).unwrap_or(u64::max_value()), Ordering::Relaxed); Poll::Ready(Ok(num_bytes)) } fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context, bufs: &[IoSlice]) -> Poll> { let this = self.project(); let num_bytes = ready!(this.inner.poll_write_vectored(cx, bufs))?; - this.sinks.upload.lock().inject(num_bytes); + this.sinks.outbound.fetch_add(u64::try_from(num_bytes).unwrap_or(u64::max_value()), Ordering::Relaxed); Poll::Ready(Ok(num_bytes)) } @@ -201,96 +205,3 @@ impl AsyncWrite for BandwidthConnecLogging { this.inner.poll_close(cx) } } - -/// Returns the number of seconds that have elapsed between an arbitrary EPOCH and now. -fn current_second() -> u32 { - lazy_static! { - static ref EPOCH: Instant = Instant::now(); - } - - EPOCH.elapsed().as_secs() as u32 -} - -/// Structure that calculates the average bandwidth over the last few seconds. -/// -/// If you want to calculate for example both download and upload bandwidths, create two different -/// objects. -struct BandwidthSink { - /// Bytes sent over the past seconds. Contains `rolling_seconds + 1` elements, where - /// `rolling_seconds` is the value passed to `new`. Only the first `rolling_seconds` elements - /// are taken into account for the average, while the last element is the element to be - /// inserted later. - bytes: SmallVec<[u64; 8]>, - /// Number of seconds between `EPOCH` and the moment we have last updated `bytes`. - latest_update: u32, -} - -impl BandwidthSink { - /// Initializes a `BandwidthSink`. - fn new(seconds: u32) -> Self { - BandwidthSink { - bytes: smallvec![0; seconds as usize + 1], - latest_update: current_second(), - } - } - - /// Returns the number of bytes over the last few seconds. The number of seconds is the value - /// configured at initialization. - fn get(&mut self) -> u64 { - self.update(); - let seconds = self.bytes.len() - 1; - self.bytes.iter() - .take(seconds) - .fold(0u64, |a, &b| a.saturating_add(b)) / seconds as u64 - } - - /// Notifies the `BandwidthSink` that a certain number of bytes have been transmitted at this - /// moment. - fn inject(&mut self, bytes: usize) { - self.update(); - if let Some(last) = self.bytes.last_mut() { - *last = last.saturating_add(bytes as u64); - } - } - - /// Updates the state of the `BandwidthSink` so that the last element of `bytes` contains the - /// current second. - fn update(&mut self) { - let current_second = current_second(); - debug_assert!(current_second >= self.latest_update); - let num_iter = cmp::min(current_second - self.latest_update, self.bytes.len() as u32); - for _ in 0..num_iter { - self.bytes.remove(0); - self.bytes.push(0); - } - self.latest_update = current_second; - } -} - -#[cfg(test)] -mod tests { - use std::{thread, time::Duration}; - use super::*; - - #[test] - fn sink_works() { - let mut sink = BandwidthSink::new(5); - sink.inject(100); - thread::sleep(Duration::from_millis(1000)); - assert_eq!(sink.get(), 20); - sink.inject(100); - thread::sleep(Duration::from_millis(1000)); - assert_eq!(sink.get(), 40); - sink.inject(100); - thread::sleep(Duration::from_millis(1000)); - assert_eq!(sink.get(), 60); - sink.inject(100); - thread::sleep(Duration::from_millis(1000)); - assert_eq!(sink.get(), 80); - sink.inject(100); - thread::sleep(Duration::from_millis(1000)); - assert_eq!(sink.get(), 100); - thread::sleep(Duration::from_millis(1000)); - assert_eq!(sink.get(), 80); - } -} diff --git a/src/transport_ext.rs b/src/transport_ext.rs index ab35b31e..e2e37fe5 100644 --- a/src/transport_ext.rs +++ b/src/transport_ext.rs @@ -21,7 +21,7 @@ //! Provides the `TransportExt` trait. use crate::{bandwidth::BandwidthLogging, bandwidth::BandwidthSinks, Transport}; -use std::{sync::Arc, time::Duration}; +use std::sync::Arc; /// Trait automatically implemented on all objects that implement `Transport`. Provides some /// additional utilities. @@ -29,13 +29,13 @@ pub trait TransportExt: Transport { /// Adds a layer on the `Transport` that logs all trafic that passes through the sockets /// created by it. /// - /// This method returns an `Arc` that can be used to retreive the bandwidth - /// values. - fn with_bandwidth_logging(self, period: Duration) -> (BandwidthLogging, Arc) + /// This method returns an `Arc` that can be used to retreive the total number + /// of bytes transferred through the sockets. + fn with_bandwidth_logging(self) -> (BandwidthLogging, Arc) where Self: Sized { - BandwidthLogging::new(self, period) + BandwidthLogging::new(self) } // TODO: add methods to easily upgrade for secio/mplex/yamux From 9178459cc8abb8379c759c02185175af7cfcea78 Mon Sep 17 00:00:00 2001 From: Demi Obenour Date: Mon, 27 Jul 2020 20:27:33 +0000 Subject: [PATCH 3/6] Automatic fixes by cargo-fix (#1662) --- core/src/connection.rs | 2 +- core/src/connection/handler.rs | 2 +- core/src/connection/listeners.rs | 4 +- core/src/connection/manager.rs | 6 +- core/src/connection/manager/task.rs | 2 +- core/src/connection/pool.rs | 8 +-- core/src/connection/substream.rs | 4 +- core/src/either.rs | 42 ++++++------- core/src/identity/error.rs | 4 +- core/src/identity/rsa.rs | 2 +- core/src/muxing.rs | 60 +++++++++---------- core/src/muxing/singleton.rs | 16 ++--- core/src/network.rs | 2 +- core/src/transport/and_then.rs | 4 +- core/src/transport/dummy.rs | 12 ++-- core/src/transport/map.rs | 4 +- core/src/transport/map_err.rs | 6 +- core/src/transport/memory.rs | 12 ++-- core/src/transport/timeout.rs | 4 +- core/src/transport/upgrade.rs | 10 ++-- core/src/upgrade/apply.rs | 4 +- core/src/upgrade/map.rs | 4 +- core/tests/util.rs | 4 +- examples/chat.rs | 2 +- examples/distributed-key-value-store.rs | 2 +- examples/gossipsub-chat.rs | 2 +- examples/ipfs-private.rs | 2 +- examples/ping.rs | 2 +- misc/core-derive/src/lib.rs | 2 +- misc/multiaddr/src/from_url.rs | 2 +- misc/multiaddr/src/lib.rs | 2 +- misc/multiaddr/tests/lib.rs | 2 +- misc/multistream-select/src/dialer_select.rs | 4 +- .../src/length_delimited.rs | 20 +++---- .../multistream-select/src/listener_select.rs | 2 +- misc/multistream-select/src/negotiated.rs | 24 ++++---- misc/multistream-select/src/protocol.rs | 20 +++---- muxers/mplex/src/lib.rs | 20 +++---- muxers/yamux/src/lib.rs | 26 ++++---- protocols/deflate/src/lib.rs | 10 ++-- protocols/floodsub/src/layer.rs | 2 +- protocols/gossipsub/src/behaviour.rs | 2 +- protocols/gossipsub/src/config.rs | 2 +- protocols/gossipsub/src/handler.rs | 2 +- protocols/gossipsub/src/mcache.rs | 2 +- protocols/gossipsub/src/topic.rs | 4 +- protocols/gossipsub/tests/smoke.rs | 2 +- protocols/identify/src/handler.rs | 2 +- protocols/identify/src/identify.rs | 2 +- protocols/kad/src/addresses.rs | 2 +- protocols/kad/src/behaviour.rs | 6 +- protocols/kad/src/handler.rs | 6 +- protocols/kad/src/jobs.rs | 6 +- protocols/kad/src/query.rs | 4 +- protocols/kad/src/query/peers/closest.rs | 2 +- .../kad/src/query/peers/closest/disjoint.rs | 6 +- protocols/kad/src/query/peers/fixed.rs | 2 +- protocols/kad/src/record/store.rs | 2 +- protocols/kad/src/record/store/memory.rs | 2 +- protocols/mdns/src/behaviour.rs | 2 +- protocols/mdns/src/service.rs | 4 +- protocols/noise/src/io.rs | 8 +-- protocols/noise/src/io/framed.rs | 8 +-- protocols/ping/src/handler.rs | 4 +- protocols/ping/src/lib.rs | 2 +- protocols/plaintext/src/lib.rs | 14 ++--- protocols/pnet/src/lib.rs | 8 +-- protocols/request-response/src/handler.rs | 2 +- protocols/request-response/src/lib.rs | 2 +- protocols/secio/src/codec/decode.rs | 8 +-- protocols/secio/src/codec/encode.rs | 8 +-- protocols/secio/src/codec/len_prefix.rs | 10 ++-- protocols/secio/src/lib.rs | 16 ++--- src/bandwidth.rs | 16 ++--- swarm/src/behaviour.rs | 2 +- swarm/src/lib.rs | 12 ++-- swarm/src/protocols_handler.rs | 2 +- swarm/src/protocols_handler/dummy.rs | 2 +- swarm/src/protocols_handler/map_in.rs | 2 +- swarm/src/protocols_handler/map_out.rs | 2 +- swarm/src/protocols_handler/multi.rs | 10 ++-- swarm/src/protocols_handler/node_handler.rs | 2 +- swarm/src/protocols_handler/one_shot.rs | 2 +- swarm/src/protocols_handler/select.rs | 2 +- swarm/src/toggle.rs | 4 +- transports/tcp/src/lib.rs | 8 +-- transports/wasm-ext/src/lib.rs | 14 ++--- transports/websocket/src/framed.rs | 10 ++-- transports/websocket/src/lib.rs | 8 +-- transports/websocket/src/tls.rs | 4 +- 90 files changed, 309 insertions(+), 309 deletions(-) diff --git a/core/src/connection.rs b/core/src/connection.rs index d160aeb2..cc1bd0a3 100644 --- a/core/src/connection.rs +++ b/core/src/connection.rs @@ -257,7 +257,7 @@ where /// Polls the connection for events produced by the associated handler /// as a result of I/O activity on the substream multiplexer. - pub fn poll(mut self: Pin<&mut Self>, cx: &mut Context) + pub fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll, ConnectionError>> { loop { diff --git a/core/src/connection/handler.rs b/core/src/connection/handler.rs index 07006f8c..625269a3 100644 --- a/core/src/connection/handler.rs +++ b/core/src/connection/handler.rs @@ -64,7 +64,7 @@ pub trait ConnectionHandler { /// Polls the handler for events. /// /// Returning an error will close the connection to the remote. - fn poll(&mut self, cx: &mut Context) + fn poll(&mut self, cx: &mut Context<'_>) -> Poll, Self::Error>>; } diff --git a/core/src/connection/listeners.rs b/core/src/connection/listeners.rs index b905b444..bfd16a77 100644 --- a/core/src/connection/listeners.rs +++ b/core/src/connection/listeners.rs @@ -230,7 +230,7 @@ where } /// Provides an API similar to `Stream`, except that it cannot end. - pub fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + pub fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { // We remove each element from `listeners` one by one and add them back. let mut remaining = self.listeners.len(); while let Some(mut listener) = self.listeners.pop_back() { @@ -310,7 +310,7 @@ where { type Item = ListenersEvent; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { ListenersStream::poll(self, cx).map(Option::Some) } } diff --git a/core/src/connection/manager.rs b/core/src/connection/manager.rs index 30d7554a..ef5d4e67 100644 --- a/core/src/connection/manager.rs +++ b/core/src/connection/manager.rs @@ -125,7 +125,7 @@ impl fmt::Debug for Manager where C: fmt::Debug, { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_map() .entries(self.tasks.iter().map(|(id, task)| (id, &task.state))) .finish() @@ -346,7 +346,7 @@ impl Manager { } /// Polls the manager for events relating to the managed connections. - pub fn poll<'a>(&'a mut self, cx: &mut Context) -> Poll> { + pub fn poll<'a>(&'a mut self, cx: &mut Context<'_>) -> Poll> { // Advance the content of `local_spawns`. while let Poll::Ready(Some(_)) = Stream::poll_next(Pin::new(&mut self.local_spawns), cx) {} @@ -468,7 +468,7 @@ impl<'a, I, C> EstablishedEntry<'a, I, C> { /// /// Returns `Err(())` if the background task associated with the connection /// is terminating and the connection is about to close. - pub fn poll_ready_notify_handler(&mut self, cx: &mut Context) -> Poll> { + pub fn poll_ready_notify_handler(&mut self, cx: &mut Context<'_>) -> Poll> { self.task.get_mut().sender.poll_ready(cx).map_err(|_| ()) } diff --git a/core/src/connection/manager/task.rs b/core/src/connection/manager/task.rs index 7ecd7145..7d715516 100644 --- a/core/src/connection/manager/task.rs +++ b/core/src/connection/manager/task.rs @@ -190,7 +190,7 @@ where // NOTE: It is imperative to always consume all incoming commands from // the manager first, in order to not prevent it from making progress because // it is blocked on the channel capacity. - 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; let id = this.id; diff --git a/core/src/connection/pool.rs b/core/src/connection/pool.rs index c4a7b83d..d89308c5 100644 --- a/core/src/connection/pool.rs +++ b/core/src/connection/pool.rs @@ -217,7 +217,7 @@ where &mut self, future: TFut, handler: THandler, - info: IncomingInfo, + info: IncomingInfo<'_>, ) -> Result where TConnInfo: ConnectionInfo + Send + 'static, @@ -254,7 +254,7 @@ where &mut self, future: TFut, handler: THandler, - info: OutgoingInfo, + info: OutgoingInfo<'_, TPeerId>, ) -> Result where TConnInfo: ConnectionInfo + Send + 'static, @@ -562,7 +562,7 @@ where /// /// > **Note**: We use a regular `poll` method instead of implementing `Stream`, /// > because we want the `Pool` to stay borrowed if necessary. - pub fn poll<'a>(&'a mut self, cx: &mut Context) -> Poll< + pub fn poll<'a>(&'a mut self, cx: &mut Context<'_>) -> Poll< PoolEvent<'a, TInEvent, TOutEvent, THandler, TTransErr, THandlerErr, TConnInfo, TPeerId> > where TConnInfo: ConnectionInfo + Clone, @@ -793,7 +793,7 @@ where /// /// Returns `Err(())` if the background task associated with the connection /// is terminating and the connection is about to close. - pub fn poll_ready_notify_handler(&mut self, cx: &mut Context) -> Poll> { + pub fn poll_ready_notify_handler(&mut self, cx: &mut Context<'_>) -> Poll> { self.entry.poll_ready_notify_handler(cx) } diff --git a/core/src/connection/substream.rs b/core/src/connection/substream.rs index cbba375c..ac537b48 100644 --- a/core/src/connection/substream.rs +++ b/core/src/connection/substream.rs @@ -150,7 +150,7 @@ where } /// Provides an API similar to `Future`. - pub fn poll(&mut self, cx: &mut Context) -> Poll, IoError>> { + pub fn poll(&mut self, cx: &mut Context<'_>) -> Poll, IoError>> { // Polling inbound substream. match self.inner.poll_event(cx) { Poll::Ready(Ok(StreamMuxerEvent::InboundSubstream(substream))) => { @@ -224,7 +224,7 @@ where { type Output = Result<(), IoError>; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { match self.muxer.close(cx) { Poll::Pending => Poll::Pending, Poll::Ready(Ok(())) => Poll::Ready(Ok(())), diff --git a/core/src/either.rs b/core/src/either.rs index 3d97c192..48257fc6 100644 --- a/core/src/either.rs +++ b/core/src/either.rs @@ -74,14 +74,14 @@ where A: AsyncRead, B: AsyncRead, { - 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> { match self.project() { EitherOutputProj::First(a) => AsyncRead::poll_read(a, cx, buf), EitherOutputProj::Second(b) => AsyncRead::poll_read(b, cx, buf), } } - fn poll_read_vectored(self: Pin<&mut Self>, cx: &mut Context, bufs: &mut [IoSliceMut]) + fn poll_read_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>]) -> Poll> { match self.project() { @@ -96,14 +96,14 @@ where A: AsyncWrite, B: 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> { match self.project() { EitherOutputProj::First(a) => AsyncWrite::poll_write(a, cx, buf), EitherOutputProj::Second(b) => AsyncWrite::poll_write(b, cx, buf), } } - fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context, bufs: &[IoSlice]) + fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>]) -> Poll> { match self.project() { @@ -112,14 +112,14 @@ where } } - fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match self.project() { EitherOutputProj::First(a) => AsyncWrite::poll_flush(a, cx), EitherOutputProj::Second(b) => AsyncWrite::poll_flush(b, cx), } } - fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match self.project() { EitherOutputProj::First(a) => AsyncWrite::poll_close(a, cx), EitherOutputProj::Second(b) => AsyncWrite::poll_close(b, cx), @@ -134,7 +134,7 @@ where { type Item = Result>; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match self.project() { EitherOutputProj::First(a) => TryStream::try_poll_next(a, cx) .map(|v| v.map(|r| r.map_err(EitherError::A))), @@ -151,7 +151,7 @@ where { type Error = EitherError; - fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match self.project() { EitherOutputProj::First(a) => Sink::poll_ready(a, cx).map_err(EitherError::A), EitherOutputProj::Second(b) => Sink::poll_ready(b, cx).map_err(EitherError::B), @@ -165,14 +165,14 @@ where } } - fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match self.project() { EitherOutputProj::First(a) => Sink::poll_flush(a, cx).map_err(EitherError::A), EitherOutputProj::Second(b) => Sink::poll_flush(b, cx).map_err(EitherError::B), } } - fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match self.project() { EitherOutputProj::First(a) => Sink::poll_close(a, cx).map_err(EitherError::A), EitherOutputProj::Second(b) => Sink::poll_close(b, cx).map_err(EitherError::B), @@ -189,7 +189,7 @@ where type OutboundSubstream = EitherOutbound; type Error = IoError; - fn poll_event(&self, cx: &mut Context) -> Poll, Self::Error>> { + fn poll_event(&self, cx: &mut Context<'_>) -> Poll, Self::Error>> { match self { EitherOutput::First(inner) => inner.poll_event(cx).map(|result| { result.map_err(|e| e.into()).map(|event| { @@ -219,7 +219,7 @@ where } } - fn poll_outbound(&self, cx: &mut Context, substream: &mut Self::OutboundSubstream) -> Poll> { + fn poll_outbound(&self, cx: &mut Context<'_>, substream: &mut Self::OutboundSubstream) -> Poll> { match (self, substream) { (EitherOutput::First(ref inner), EitherOutbound::A(ref mut substream)) => { inner.poll_outbound(cx, substream).map(|p| p.map(EitherOutput::First)).map_err(|e| e.into()) @@ -248,7 +248,7 @@ where } } - fn read_substream(&self, cx: &mut Context, sub: &mut Self::Substream, buf: &mut [u8]) -> Poll> { + fn read_substream(&self, cx: &mut Context<'_>, sub: &mut Self::Substream, buf: &mut [u8]) -> Poll> { match (self, sub) { (EitherOutput::First(ref inner), EitherOutput::First(ref mut sub)) => { inner.read_substream(cx, sub, buf).map_err(|e| e.into()) @@ -260,7 +260,7 @@ where } } - fn write_substream(&self, cx: &mut Context, sub: &mut Self::Substream, buf: &[u8]) -> Poll> { + fn write_substream(&self, cx: &mut Context<'_>, sub: &mut Self::Substream, buf: &[u8]) -> Poll> { match (self, sub) { (EitherOutput::First(ref inner), EitherOutput::First(ref mut sub)) => { inner.write_substream(cx, sub, buf).map_err(|e| e.into()) @@ -272,7 +272,7 @@ where } } - fn flush_substream(&self, cx: &mut Context, sub: &mut Self::Substream) -> Poll> { + fn flush_substream(&self, cx: &mut Context<'_>, sub: &mut Self::Substream) -> Poll> { match (self, sub) { (EitherOutput::First(ref inner), EitherOutput::First(ref mut sub)) => { inner.flush_substream(cx, sub).map_err(|e| e.into()) @@ -284,7 +284,7 @@ where } } - fn shutdown_substream(&self, cx: &mut Context, sub: &mut Self::Substream) -> Poll> { + fn shutdown_substream(&self, cx: &mut Context<'_>, sub: &mut Self::Substream) -> Poll> { match (self, sub) { (EitherOutput::First(ref inner), EitherOutput::First(ref mut sub)) => { inner.shutdown_substream(cx, sub).map_err(|e| e.into()) @@ -313,14 +313,14 @@ where } } - fn close(&self, cx: &mut Context) -> Poll> { + fn close(&self, cx: &mut Context<'_>) -> Poll> { match self { EitherOutput::First(inner) => inner.close(cx).map_err(|e| e.into()), EitherOutput::Second(inner) => inner.close(cx).map_err(|e| e.into()), } } - fn flush_all(&self, cx: &mut Context) -> Poll> { + fn flush_all(&self, cx: &mut Context<'_>) -> Poll> { match self { EitherOutput::First(inner) => inner.flush_all(cx).map_err(|e| e.into()), EitherOutput::Second(inner) => inner.flush_all(cx).map_err(|e| e.into()), @@ -351,7 +351,7 @@ where { type Item = Result, EitherError>, EitherError>; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match self.project() { EitherListenStreamProj::First(a) => match TryStream::try_poll_next(a, cx) { Poll::Pending => Poll::Pending, @@ -385,7 +385,7 @@ where { type Output = Result, EitherError>; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { match self.project() { EitherFutureProj::First(a) => TryFuture::try_poll(a, cx) .map_ok(EitherOutput::First).map_err(EitherError::A), @@ -407,7 +407,7 @@ where { type Output = Result, EitherError>; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { match self.project() { EitherFuture2Proj::A(a) => TryFuture::try_poll(a, cx) .map_ok(EitherOutput::First).map_err(EitherError::A), diff --git a/core/src/identity/error.rs b/core/src/identity/error.rs index d89967a7..8fd1b1b9 100644 --- a/core/src/identity/error.rs +++ b/core/src/identity/error.rs @@ -41,7 +41,7 @@ impl DecodingError { } impl fmt::Display for DecodingError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Key decoding error: {}", self.msg) } } @@ -71,7 +71,7 @@ impl SigningError { } impl fmt::Display for SigningError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Key signing error: {}", self.msg) } } diff --git a/core/src/identity/rsa.rs b/core/src/identity/rsa.rs index 7b699b08..898b4cb1 100644 --- a/core/src/identity/rsa.rs +++ b/core/src/identity/rsa.rs @@ -230,7 +230,7 @@ mod tests { struct SomeKeypair(Keypair); impl fmt::Debug for SomeKeypair { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SomeKeypair") } } diff --git a/core/src/muxing.rs b/core/src/muxing.rs index e4c2e63c..1b0b9749 100644 --- a/core/src/muxing.rs +++ b/core/src/muxing.rs @@ -92,7 +92,7 @@ pub trait StreamMuxer { /// Only the latest task that was used to call this method may be notified. /// /// An error can be generated if the connection has been closed. - fn poll_event(&self, cx: &mut Context) -> Poll, Self::Error>>; + fn poll_event(&self, cx: &mut Context<'_>) -> Poll, Self::Error>>; /// Opens a new outgoing substream, and produces the equivalent to a future that will be /// resolved when it becomes available. @@ -110,7 +110,7 @@ pub trait StreamMuxer { /// /// May panic or produce an undefined result if an earlier polling of the same substream /// returned `Ready` or `Err`. - fn poll_outbound(&self, cx: &mut Context, s: &mut Self::OutboundSubstream) + fn poll_outbound(&self, cx: &mut Context<'_>, s: &mut Self::OutboundSubstream) -> Poll>; /// Destroys an outbound substream future. Use this after the outbound substream has finished, @@ -128,7 +128,7 @@ pub trait StreamMuxer { /// /// An error can be generated if the connection has been closed, or if a protocol misbehaviour /// happened. - fn read_substream(&self, cx: &mut Context, s: &mut Self::Substream, buf: &mut [u8]) + fn read_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream, buf: &mut [u8]) -> Poll>; /// Write data to a substream. The behaviour is the same as `futures::AsyncWrite::poll_write`. @@ -142,7 +142,7 @@ pub trait StreamMuxer { /// /// It is incorrect to call this method on a substream if you called `shutdown_substream` on /// this substream earlier. - fn write_substream(&self, cx: &mut Context, s: &mut Self::Substream, buf: &[u8]) + fn write_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream, buf: &[u8]) -> Poll>; /// Flushes a substream. The behaviour is the same as `futures::AsyncWrite::poll_flush`. @@ -155,7 +155,7 @@ pub trait StreamMuxer { /// call this method may be notified. /// /// > **Note**: This method may be implemented as a call to `flush_all`. - fn flush_substream(&self, cx: &mut Context, s: &mut Self::Substream) + fn flush_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream) -> Poll>; /// Attempts to shut down the writing side of a substream. The behaviour is similar to @@ -169,7 +169,7 @@ pub trait StreamMuxer { /// /// An error can be generated if the connection has been closed, or if a protocol misbehaviour /// happened. - fn shutdown_substream(&self, cx: &mut Context, s: &mut Self::Substream) + fn shutdown_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream) -> Poll>; /// Destroys a substream. @@ -198,14 +198,14 @@ pub trait StreamMuxer { /// > that the remote is properly informed of the shutdown. However, apart from /// > properly informing the remote, there is no difference between this and /// > immediately dropping the muxer. - fn close(&self, cx: &mut Context) -> Poll>; + fn close(&self, cx: &mut Context<'_>) -> Poll>; /// Flush this `StreamMuxer`. /// /// This drains any write buffers of substreams and delivers any pending shutdown notifications /// due to `shutdown_substream` or `close`. One may thus shutdown groups of substreams /// followed by a final `flush_all` instead of having to do `flush_substream` for each. - fn flush_all(&self, cx: &mut Context) -> Poll>; + fn flush_all(&self, cx: &mut Context<'_>) -> Poll>; } /// Event about a connection, reported by an implementation of [`StreamMuxer`]. @@ -280,7 +280,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 { match Future::poll(Pin::new(&mut self.inner), cx) { Poll::Ready(Ok(substream)) => { let out = substream_from_ref(self.inner.muxer.clone(), substream); @@ -329,7 +329,7 @@ where { type Output = Result<::Substream, ::Error>; - fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { // We use a `this` because the compiler isn't smart enough to allow mutably borrowing // multiple different fields from the `Pin` at the same time. let this = &mut *self; @@ -405,7 +405,7 @@ where P: Deref, P::Target: StreamMuxer, { - 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> { // We use a `this` because the compiler isn't smart enough to allow mutably borrowing // multiple different fields from the `Pin` at the same time. let this = &mut *self; @@ -420,7 +420,7 @@ where P: Deref, P::Target: StreamMuxer, { - 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> { // We use a `this` because the compiler isn't smart enough to allow mutably borrowing // multiple different fields from the `Pin` at the same time. let this = &mut *self; @@ -429,7 +429,7 @@ where this.muxer.write_substream(cx, s, buf).map_err(|e| e.into()) } - fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { // We use a `this` because the compiler isn't smart enough to allow mutably borrowing // multiple different fields from the `Pin` at the same time. let this = &mut *self; @@ -458,7 +458,7 @@ where } } - fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { // We use a `this` because the compiler isn't smart enough to allow mutably borrowing // multiple different fields from the `Pin` at the same time. let this = &mut *self; @@ -511,7 +511,7 @@ impl StreamMuxer for StreamMuxerBox { type Error = io::Error; #[inline] - fn poll_event(&self, cx: &mut Context) -> Poll, Self::Error>> { + fn poll_event(&self, cx: &mut Context<'_>) -> Poll, Self::Error>> { self.inner.poll_event(cx) } @@ -521,7 +521,7 @@ impl StreamMuxer for StreamMuxerBox { } #[inline] - fn poll_outbound(&self, cx: &mut Context, s: &mut Self::OutboundSubstream) -> Poll> { + fn poll_outbound(&self, cx: &mut Context<'_>, s: &mut Self::OutboundSubstream) -> Poll> { self.inner.poll_outbound(cx, s) } @@ -531,22 +531,22 @@ impl StreamMuxer for StreamMuxerBox { } #[inline] - fn read_substream(&self, cx: &mut Context, s: &mut Self::Substream, buf: &mut [u8]) -> Poll> { + fn read_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream, buf: &mut [u8]) -> Poll> { self.inner.read_substream(cx, s, buf) } #[inline] - fn write_substream(&self, cx: &mut Context, s: &mut Self::Substream, buf: &[u8]) -> Poll> { + fn write_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream, buf: &[u8]) -> Poll> { self.inner.write_substream(cx, s, buf) } #[inline] - fn flush_substream(&self, cx: &mut Context, s: &mut Self::Substream) -> Poll> { + fn flush_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream) -> Poll> { self.inner.flush_substream(cx, s) } #[inline] - fn shutdown_substream(&self, cx: &mut Context, s: &mut Self::Substream) -> Poll> { + fn shutdown_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream) -> Poll> { self.inner.shutdown_substream(cx, s) } @@ -556,12 +556,12 @@ impl StreamMuxer for StreamMuxerBox { } #[inline] - fn close(&self, cx: &mut Context) -> Poll> { + fn close(&self, cx: &mut Context<'_>) -> Poll> { self.inner.close(cx) } #[inline] - fn flush_all(&self, cx: &mut Context) -> Poll> { + fn flush_all(&self, cx: &mut Context<'_>) -> Poll> { self.inner.flush_all(cx) } } @@ -583,7 +583,7 @@ where type Error = io::Error; #[inline] - fn poll_event(&self, cx: &mut Context) -> Poll, Self::Error>> { + fn poll_event(&self, cx: &mut Context<'_>) -> Poll, Self::Error>> { let substream = match self.inner.poll_event(cx) { Poll::Pending => return Poll::Pending, Poll::Ready(Ok(StreamMuxerEvent::AddressChange(a))) => @@ -608,7 +608,7 @@ where #[inline] fn poll_outbound( &self, - cx: &mut Context, + cx: &mut Context<'_>, substream: &mut Self::OutboundSubstream, ) -> Poll> { let mut list = self.outbound.lock(); @@ -629,25 +629,25 @@ where } #[inline] - fn read_substream(&self, cx: &mut Context, s: &mut Self::Substream, buf: &mut [u8]) -> Poll> { + fn read_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream, buf: &mut [u8]) -> Poll> { let mut list = self.substreams.lock(); self.inner.read_substream(cx, list.get_mut(s).unwrap(), buf).map_err(|e| e.into()) } #[inline] - fn write_substream(&self, cx: &mut Context, s: &mut Self::Substream, buf: &[u8]) -> Poll> { + fn write_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream, buf: &[u8]) -> Poll> { let mut list = self.substreams.lock(); self.inner.write_substream(cx, list.get_mut(s).unwrap(), buf).map_err(|e| e.into()) } #[inline] - fn flush_substream(&self, cx: &mut Context, s: &mut Self::Substream) -> Poll> { + fn flush_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream) -> Poll> { let mut list = self.substreams.lock(); self.inner.flush_substream(cx, list.get_mut(s).unwrap()).map_err(|e| e.into()) } #[inline] - fn shutdown_substream(&self, cx: &mut Context, s: &mut Self::Substream) -> Poll> { + fn shutdown_substream(&self, cx: &mut Context<'_>, s: &mut Self::Substream) -> Poll> { let mut list = self.substreams.lock(); self.inner.shutdown_substream(cx, list.get_mut(s).unwrap()).map_err(|e| e.into()) } @@ -659,12 +659,12 @@ where } #[inline] - fn close(&self, cx: &mut Context) -> Poll> { + fn close(&self, cx: &mut Context<'_>) -> Poll> { self.inner.close(cx).map_err(|e| e.into()) } #[inline] - fn flush_all(&self, cx: &mut Context) -> Poll> { + fn flush_all(&self, cx: &mut Context<'_>) -> Poll> { self.inner.flush_all(cx).map_err(|e| e.into()) } } diff --git a/core/src/muxing/singleton.rs b/core/src/muxing/singleton.rs index e3a6c3b2..47701f07 100644 --- a/core/src/muxing/singleton.rs +++ b/core/src/muxing/singleton.rs @@ -65,7 +65,7 @@ where type OutboundSubstream = OutboundSubstream; type Error = io::Error; - fn poll_event(&self, _: &mut Context) -> Poll, io::Error>> { + fn poll_event(&self, _: &mut Context<'_>) -> Poll, io::Error>> { match self.endpoint { Endpoint::Dialer => return Poll::Pending, Endpoint::Listener => {} @@ -82,7 +82,7 @@ where OutboundSubstream {} } - fn poll_outbound(&self, _: &mut Context, _: &mut Self::OutboundSubstream) -> Poll> { + fn poll_outbound(&self, _: &mut Context<'_>, _: &mut Self::OutboundSubstream) -> Poll> { match self.endpoint { Endpoint::Listener => return Poll::Pending, Endpoint::Dialer => {} @@ -98,31 +98,31 @@ where fn destroy_outbound(&self, _: Self::OutboundSubstream) { } - fn read_substream(&self, cx: &mut Context, _: &mut Self::Substream, buf: &mut [u8]) -> Poll> { + fn read_substream(&self, cx: &mut Context<'_>, _: &mut Self::Substream, buf: &mut [u8]) -> Poll> { AsyncRead::poll_read(Pin::new(&mut *self.inner.lock()), cx, buf) } - fn write_substream(&self, cx: &mut Context, _: &mut Self::Substream, buf: &[u8]) -> Poll> { + fn write_substream(&self, cx: &mut Context<'_>, _: &mut Self::Substream, buf: &[u8]) -> Poll> { AsyncWrite::poll_write(Pin::new(&mut *self.inner.lock()), cx, buf) } - fn flush_substream(&self, cx: &mut Context, _: &mut Self::Substream) -> Poll> { + fn flush_substream(&self, cx: &mut Context<'_>, _: &mut Self::Substream) -> Poll> { AsyncWrite::poll_flush(Pin::new(&mut *self.inner.lock()), cx) } - fn shutdown_substream(&self, cx: &mut Context, _: &mut Self::Substream) -> Poll> { + fn shutdown_substream(&self, cx: &mut Context<'_>, _: &mut Self::Substream) -> Poll> { AsyncWrite::poll_close(Pin::new(&mut *self.inner.lock()), cx) } fn destroy_substream(&self, _: Self::Substream) { } - fn close(&self, cx: &mut Context) -> Poll> { + fn close(&self, cx: &mut Context<'_>) -> Poll> { // The `StreamMuxer` trait requires that `close()` implies `flush_all()`. self.flush_all(cx) } - fn flush_all(&self, cx: &mut Context) -> Poll> { + fn flush_all(&self, cx: &mut Context<'_>) -> Poll> { AsyncWrite::poll_flush(Pin::new(&mut *self.inner.lock()), cx) } } diff --git a/core/src/network.rs b/core/src/network.rs index f57f25f3..e1220143 100644 --- a/core/src/network.rs +++ b/core/src/network.rs @@ -327,7 +327,7 @@ where } /// Provides an API similar to `Stream`, except that it cannot error. - pub fn poll<'a>(&'a mut self, cx: &mut Context) -> Poll> + pub fn poll<'a>(&'a mut self, cx: &mut Context<'_>) -> Poll> where TTrans: Transport, TTrans::Error: Send + 'static, diff --git a/core/src/transport/and_then.rs b/core/src/transport/and_then.rs index bd7ee426..ba751328 100644 --- a/core/src/transport/and_then.rs +++ b/core/src/transport/and_then.rs @@ -94,7 +94,7 @@ where EitherError >; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.project(); match TryStream::try_poll_next(this.stream, cx) { Poll::Ready(Some(Ok(event))) => { @@ -146,7 +146,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 { let future = match &mut self.inner { Either::Left(future) => { diff --git a/core/src/transport/dummy.rs b/core/src/transport/dummy.rs index 046f77c6..0f9ee672 100644 --- a/core/src/transport/dummy.rs +++ b/core/src/transport/dummy.rs @@ -42,7 +42,7 @@ impl Default for DummyTransport { } impl fmt::Debug for DummyTransport { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "DummyTransport") } } @@ -73,13 +73,13 @@ impl Transport for DummyTransport { pub struct DummyStream(()); impl fmt::Debug for DummyStream { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "DummyStream") } } impl AsyncRead for DummyStream { - fn poll_read(self: Pin<&mut Self>, _: &mut Context, _: &mut [u8]) + fn poll_read(self: Pin<&mut Self>, _: &mut Context<'_>, _: &mut [u8]) -> Poll> { Poll::Ready(Err(io::ErrorKind::Other.into())) @@ -87,19 +87,19 @@ impl AsyncRead for DummyStream { } impl AsyncWrite for DummyStream { - fn poll_write(self: Pin<&mut Self>, _: &mut Context, _: &[u8]) + fn poll_write(self: Pin<&mut Self>, _: &mut Context<'_>, _: &[u8]) -> Poll> { Poll::Ready(Err(io::ErrorKind::Other.into())) } - fn poll_flush(self: Pin<&mut Self>, _: &mut Context) + fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { Poll::Ready(Err(io::ErrorKind::Other.into())) } - fn poll_close(self: Pin<&mut Self>, _: &mut Context) + fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { Poll::Ready(Err(io::ErrorKind::Other.into())) diff --git a/core/src/transport/map.rs b/core/src/transport/map.rs index 3de9f35d..f9fb2cf7 100644 --- a/core/src/transport/map.rs +++ b/core/src/transport/map.rs @@ -74,7 +74,7 @@ where { type Item = Result, E>, E>; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.project(); match TryStream::try_poll_next(this.stream, cx) { Poll::Ready(Some(Ok(event))) => { @@ -124,7 +124,7 @@ where { type Output = Result; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.project(); let item = match TryFuture::try_poll(this.inner, cx) { Poll::Pending => return Poll::Pending, diff --git a/core/src/transport/map_err.rs b/core/src/transport/map_err.rs index aacd2128..90e65eb2 100644 --- a/core/src/transport/map_err.rs +++ b/core/src/transport/map_err.rs @@ -82,7 +82,7 @@ where { type Item = Result, TErr>, TErr>; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.project(); match TryStream::try_poll_next(this.inner, cx) { Poll::Ready(Some(Ok(event))) => { @@ -118,7 +118,7 @@ where T: Transport, { type Output = Result; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.project(); match Future::poll(this.inner, cx) { Poll::Ready(Ok(value)) => Poll::Ready(Ok(value)), @@ -146,7 +146,7 @@ where { type Output = Result; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.project(); match Future::poll(this.inner, cx) { Poll::Ready(Ok(value)) => Poll::Ready(Ok(value)), diff --git a/core/src/transport/memory.rs b/core/src/transport/memory.rs index 2f27e126..713cb4f1 100644 --- a/core/src/transport/memory.rs +++ b/core/src/transport/memory.rs @@ -46,7 +46,7 @@ pub struct DialFuture { impl Future for DialFuture { type Output = Result>, MemoryTransportError>; - fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { match self.sender.poll_ready(cx) { Poll::Pending => return Poll::Pending, Poll::Ready(Ok(())) => {}, @@ -175,7 +175,7 @@ pub struct Listener { impl Stream for Listener { type Item = Result>, MemoryTransportError>>, MemoryTransportError>, MemoryTransportError>; - 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.tell_listen_addr { self.tell_listen_addr = false; return Poll::Ready(Some(Ok(ListenerEvent::NewAddress(self.addr.clone())))) @@ -240,7 +240,7 @@ impl Unpin for Chan { impl Stream for Chan { 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> { match Stream::poll_next(Pin::new(&mut self.incoming), cx) { Poll::Pending => Poll::Pending, Poll::Ready(None) => Poll::Ready(Some(Err(io::ErrorKind::BrokenPipe.into()))), @@ -252,7 +252,7 @@ impl Stream for Chan { impl Sink for Chan { 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> { self.outgoing.poll_ready(cx) .map(|v| v.map_err(|_| io::ErrorKind::BrokenPipe.into())) } @@ -261,11 +261,11 @@ impl Sink for Chan { self.outgoing.start_send(item).map_err(|_| io::ErrorKind::BrokenPipe.into()) } - fn poll_flush(self: Pin<&mut Self>, _: &mut Context) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } - fn poll_close(self: Pin<&mut Self>, _: &mut Context) -> Poll> { + fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } } diff --git a/core/src/transport/timeout.rs b/core/src/transport/timeout.rs index 4f45756e..dc29af81 100644 --- a/core/src/transport/timeout.rs +++ b/core/src/transport/timeout.rs @@ -118,7 +118,7 @@ where { type Item = Result, TransportTimeoutError>, TransportTimeoutError>; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.project(); let poll_out = match TryStream::try_poll_next(this.inner, cx) { @@ -160,7 +160,7 @@ where { type Output = Result>; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { // It is debatable whether we should poll the inner future first or the timer first. // For example, if you start dialing with a timeout of 10 seconds, then after 15 seconds // the dialing succeeds on the wire, then after 20 seconds you poll, then depending on diff --git a/core/src/transport/upgrade.rs b/core/src/transport/upgrade.rs index bd862dd8..16784178 100644 --- a/core/src/transport/upgrade.rs +++ b/core/src/transport/upgrade.rs @@ -194,7 +194,7 @@ where { type Output = as Future>::Output; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.project(); Future::poll(this.inner, cx) } @@ -223,7 +223,7 @@ where { type Output = Result<(I, M), UpgradeError>; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.project(); let m = match ready!(Future::poll(this.upgrade, cx)) { Ok(m) => m, @@ -337,7 +337,7 @@ where { type Output = Result<(I, D), TransportUpgradeError>; - fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { // We use a `this` variable because the compiler can't mutably borrow multiple times // accross a `Deref`. let this = &mut *self; @@ -387,7 +387,7 @@ where { type Item = Result, TransportUpgradeError>, TransportUpgradeError>; - 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!(TryStream::try_poll_next(self.stream.as_mut(), cx)) { Some(Ok(event)) => { let event = event @@ -430,7 +430,7 @@ where { type Output = Result<(I, D), TransportUpgradeError>; - fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { // We use a `this` variable because the compiler can't mutably borrow multiple times // accross a `Deref`. let this = &mut *self; diff --git a/core/src/upgrade/apply.rs b/core/src/upgrade/apply.rs index f3bee044..eaf25e88 100644 --- a/core/src/upgrade/apply.rs +++ b/core/src/upgrade/apply.rs @@ -105,7 +105,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 mem::replace(&mut self.inner, InboundUpgradeApplyState::Undefined) { InboundUpgradeApplyState::Init { mut future, upgrade } => { @@ -181,7 +181,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 mem::replace(&mut self.inner, OutboundUpgradeApplyState::Undefined) { OutboundUpgradeApplyState::Init { mut future, upgrade } => { diff --git a/core/src/upgrade/map.rs b/core/src/upgrade/map.rs index d55971df..2f5ca31e 100644 --- a/core/src/upgrade/map.rs +++ b/core/src/upgrade/map.rs @@ -244,7 +244,7 @@ where { type Output = Result; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.project(); let item = match TryFuture::try_poll(this.inner, cx) { Poll::Ready(Ok(v)) => v, @@ -271,7 +271,7 @@ where { type Output = Result; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.project(); match TryFuture::try_poll(this.fut, cx) { Poll::Pending => Poll::Pending, diff --git a/core/tests/util.rs b/core/tests/util.rs index 40a60ccc..306728d6 100644 --- a/core/tests/util.rs +++ b/core/tests/util.rs @@ -32,7 +32,7 @@ impl ConnectionHandler for TestHandler { fn inject_address_change(&mut self, _: &Multiaddr) {} - fn poll(&mut self, _: &mut Context) + fn poll(&mut self, _: &mut Context<'_>) -> Poll, Self::Error>> { Poll::Ready(Ok(ConnectionHandlerEvent::Custom(()))) @@ -63,7 +63,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 std::mem::replace(&mut self.state, CloseMuxerState::Done) { CloseMuxerState::Close(muxer) => { diff --git a/examples/chat.rs b/examples/chat.rs index c75b27cb..ba82849d 100644 --- a/examples/chat.rs +++ b/examples/chat.rs @@ -147,7 +147,7 @@ fn main() -> Result<(), Box> { // Kick it off let mut listening = false; - task::block_on(future::poll_fn(move |cx: &mut Context| { + task::block_on(future::poll_fn(move |cx: &mut Context<'_>| { loop { match stdin.try_poll_next_unpin(cx)? { Poll::Ready(Some(line)) => swarm.floodsub.publish(floodsub_topic.clone(), line.as_bytes()), diff --git a/examples/distributed-key-value-store.rs b/examples/distributed-key-value-store.rs index 71773c00..e7b80d00 100644 --- a/examples/distributed-key-value-store.rs +++ b/examples/distributed-key-value-store.rs @@ -132,7 +132,7 @@ fn main() -> Result<(), Box> { // Kick it off. let mut listening = false; - task::block_on(future::poll_fn(move |cx: &mut Context| { + task::block_on(future::poll_fn(move |cx: &mut Context<'_>| { loop { match stdin.try_poll_next_unpin(cx)? { Poll::Ready(Some(line)) => handle_input_line(&mut swarm.kademlia, line), diff --git a/examples/gossipsub-chat.rs b/examples/gossipsub-chat.rs index b7ef6faf..4aafb468 100644 --- a/examples/gossipsub-chat.rs +++ b/examples/gossipsub-chat.rs @@ -118,7 +118,7 @@ fn main() -> Result<(), Box> { // Kick it off let mut listening = false; - task::block_on(future::poll_fn(move |cx: &mut Context| { + task::block_on(future::poll_fn(move |cx: &mut Context<'_>| { loop { match stdin.try_poll_next_unpin(cx)? { Poll::Ready(Some(line)) => swarm.publish(&topic, line.as_bytes()), diff --git a/examples/ipfs-private.rs b/examples/ipfs-private.rs index 9d347685..f70f4404 100644 --- a/examples/ipfs-private.rs +++ b/examples/ipfs-private.rs @@ -278,7 +278,7 @@ fn main() -> Result<(), Box> { // Kick it off let mut listening = false; - task::block_on(future::poll_fn(move |cx: &mut Context| { + task::block_on(future::poll_fn(move |cx: &mut Context<'_>| { loop { match stdin.try_poll_next_unpin(cx)? { Poll::Ready(Some(line)) => { diff --git a/examples/ping.rs b/examples/ping.rs index aa9e1f8d..eb5fa762 100644 --- a/examples/ping.rs +++ b/examples/ping.rs @@ -77,7 +77,7 @@ fn main() -> Result<(), Box> { Swarm::listen_on(&mut swarm, "/ip4/0.0.0.0/tcp/0".parse()?)?; let mut listening = false; - task::block_on(future::poll_fn(move |cx: &mut Context| { + task::block_on(future::poll_fn(move |cx: &mut Context<'_>| { loop { match swarm.poll_next_unpin(cx) { Poll::Ready(Some(event)) => println!("{:?}", event), diff --git a/misc/core-derive/src/lib.rs b/misc/core-derive/src/lib.rs index c100b516..8f873dd0 100644 --- a/misc/core-derive/src/lib.rs +++ b/misc/core-derive/src/lib.rs @@ -20,7 +20,7 @@ #![recursion_limit = "256"] -extern crate proc_macro; + use quote::quote; use proc_macro::TokenStream; diff --git a/misc/multiaddr/src/from_url.rs b/misc/multiaddr/src/from_url.rs index 738ed20b..aac19c2d 100644 --- a/misc/multiaddr/src/from_url.rs +++ b/misc/multiaddr/src/from_url.rs @@ -121,7 +121,7 @@ pub enum FromUrlErr { } impl fmt::Display for FromUrlErr { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { FromUrlErr::BadUrl => write!(f, "Bad URL"), FromUrlErr::UnsupportedScheme => write!(f, "Unrecognized URL scheme"), diff --git a/misc/multiaddr/src/lib.rs b/misc/multiaddr/src/lib.rs index da1a729c..60c2ff8d 100644 --- a/misc/multiaddr/src/lib.rs +++ b/misc/multiaddr/src/lib.rs @@ -143,7 +143,7 @@ impl Multiaddr { /// updated `Protocol` at position `at` will be returned. pub fn replace<'a, F>(&self, at: usize, by: F) -> Option where - F: FnOnce(&Protocol) -> Option> + F: FnOnce(&Protocol<'_>) -> Option> { let mut address = Multiaddr::with_capacity(self.len()); let mut fun = Some(by); diff --git a/misc/multiaddr/tests/lib.rs b/misc/multiaddr/tests/lib.rs index d0928022..1589ec27 100644 --- a/misc/multiaddr/tests/lib.rs +++ b/misc/multiaddr/tests/lib.rs @@ -335,7 +335,7 @@ fn append() { assert_eq!(None, i.next()) } -fn replace_ip_addr(a: &Multiaddr, p: Protocol) -> Option { +fn replace_ip_addr(a: &Multiaddr, p: Protocol<'_>) -> Option { a.replace(0, move |x| match x { Protocol::Ip4(_) | Protocol::Ip6(_) => Some(p), _ => None diff --git a/misc/multistream-select/src/dialer_select.rs b/misc/multistream-select/src/dialer_select.rs index 1f7bffda..e0c03c73 100644 --- a/misc/multistream-select/src/dialer_select.rs +++ b/misc/multistream-select/src/dialer_select.rs @@ -163,7 +163,7 @@ where { type Output = Result<(I::Item, Negotiated), NegotiationError>; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.project(); loop { @@ -300,7 +300,7 @@ where { type Output = Result<(I::Item, Negotiated), NegotiationError>; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.project(); loop { diff --git a/misc/multistream-select/src/length_delimited.rs b/misc/multistream-select/src/length_delimited.rs index f75d9703..da7bc632 100644 --- a/misc/multistream-select/src/length_delimited.rs +++ b/misc/multistream-select/src/length_delimited.rs @@ -110,7 +110,7 @@ impl LengthDelimited { /// /// After this method returns `Poll::Ready`, the write buffer of frames /// submitted to the `Sink` is guaranteed to be empty. - pub fn poll_write_buffer(self: Pin<&mut Self>, cx: &mut Context) + pub fn poll_write_buffer(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> where R: AsyncWrite @@ -140,7 +140,7 @@ where { type Item = Result; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let mut this = self.project(); loop { @@ -212,7 +212,7 @@ where { 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> { // Use the maximum frame length also as a (soft) upper limit // for the entire write buffer. The actual (hard) limit is thus // implied to be roughly 2 * MAX_FRAME_SIZE. @@ -250,7 +250,7 @@ where 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> { // Write all buffered frame data to the underlying I/O stream. match LengthDelimited::poll_write_buffer(self.as_mut(), cx) { Poll::Ready(Ok(())) => {}, @@ -265,7 +265,7 @@ where this.inner.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> { // Write all buffered frame data to the underlying I/O stream. match LengthDelimited::poll_write_buffer(self.as_mut(), cx) { Poll::Ready(Ok(())) => {}, @@ -314,7 +314,7 @@ where { type Item = Result; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.project().inner.poll_next(cx) } } @@ -323,7 +323,7 @@ impl AsyncWrite for LengthDelimitedReader where R: AsyncWrite { - fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) + fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { // `this` here designates the `LengthDelimited`. @@ -340,15 +340,15 @@ where this.project().inner.poll_write(cx, buf) } - fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.project().inner.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.project().inner.poll_close(cx) } - fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context, bufs: &[IoSlice]) + fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>]) -> Poll> { // `this` here designates the `LengthDelimited`. diff --git a/misc/multistream-select/src/listener_select.rs b/misc/multistream-select/src/listener_select.rs index 93e8ec61..7a71c9ef 100644 --- a/misc/multistream-select/src/listener_select.rs +++ b/misc/multistream-select/src/listener_select.rs @@ -101,7 +101,7 @@ where { type Output = Result<(N, Negotiated), NegotiationError>; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.project(); loop { diff --git a/misc/multistream-select/src/negotiated.rs b/misc/multistream-select/src/negotiated.rs index f309ba9e..f3f9ed9e 100644 --- a/misc/multistream-select/src/negotiated.rs +++ b/misc/multistream-select/src/negotiated.rs @@ -57,7 +57,7 @@ where { type Output = Result, NegotiationError>; - fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let mut io = self.inner.take().expect("NegotiatedFuture called after completion."); match Negotiated::poll(Pin::new(&mut io), cx) { Poll::Pending => { @@ -87,7 +87,7 @@ impl Negotiated { } /// Polls the `Negotiated` for completion. - fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> where TInner: AsyncRead + AsyncWrite + Unpin { @@ -191,7 +191,7 @@ impl AsyncRead for Negotiated where TInner: AsyncRead + AsyncWrite + Unpin { - fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) + fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll> { loop { @@ -225,7 +225,7 @@ where } }*/ - fn poll_read_vectored(mut self: Pin<&mut Self>, cx: &mut Context, bufs: &mut [IoSliceMut]) + fn poll_read_vectored(mut self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>]) -> Poll> { loop { @@ -255,7 +255,7 @@ impl AsyncWrite for Negotiated where TInner: AsyncWrite + AsyncRead + Unpin { - 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> { match self.project().state.project() { StateProj::Completed { mut io, remaining } => { while !remaining.is_empty() { @@ -272,7 +272,7 @@ where } } - fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match self.project().state.project() { StateProj::Completed { mut io, remaining } => { while !remaining.is_empty() { @@ -289,7 +289,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> { // Ensure all data has been flushed and expected negotiation messages // have been received. ready!(self.as_mut().poll(cx).map_err(Into::::into)?); @@ -303,7 +303,7 @@ where } } - fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context, bufs: &[IoSlice]) + fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>]) -> Poll> { match self.project().state.project() { @@ -384,13 +384,13 @@ mod tests { struct Capped { buf: Vec, step: usize } impl AsyncRead for Capped { - fn poll_read(self: Pin<&mut Self>, _: &mut Context, _: &mut [u8]) -> Poll> { + fn poll_read(self: Pin<&mut Self>, _: &mut Context<'_>, _: &mut [u8]) -> Poll> { unreachable!() } } impl AsyncWrite for Capped { - 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> { if self.buf.len() + buf.len() > self.buf.capacity() { return Poll::Ready(Err(io::ErrorKind::WriteZero.into())) } @@ -399,11 +399,11 @@ mod tests { Poll::Ready(Ok(n)) } - fn poll_flush(self: Pin<&mut Self>, _: &mut Context) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } - fn poll_close(self: Pin<&mut Self>, _: &mut Context) -> Poll> { + fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } } diff --git a/misc/multistream-select/src/protocol.rs b/misc/multistream-select/src/protocol.rs index 1c184a31..846a4167 100644 --- a/misc/multistream-select/src/protocol.rs +++ b/misc/multistream-select/src/protocol.rs @@ -316,7 +316,7 @@ where { type Error = ProtocolError; - fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.project().inner.poll_ready(cx).map_err(From::from) } @@ -326,11 +326,11 @@ where self.project().inner.start_send(buf.freeze()).map_err(From::from) } - fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.project().inner.poll_flush(cx).map_err(From::from) } - fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.project().inner.poll_close(cx).map_err(From::from) } } @@ -341,7 +341,7 @@ where { type Item = Result; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { match poll_stream(self.project().inner, cx) { Poll::Pending => Poll::Pending, Poll::Ready(None) => Poll::Ready(None), @@ -388,7 +388,7 @@ where { type Item = Result; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { poll_stream(self.project().inner, cx) } } @@ -397,24 +397,24 @@ impl AsyncWrite for MessageReader where TInner: 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.project().inner.poll_write(cx, buf) } - fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.project().inner.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.project().inner.poll_close(cx) } - 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.project().inner.poll_write_vectored(cx, bufs) } } -fn poll_stream(stream: Pin<&mut S>, cx: &mut Context) -> Poll>> +fn poll_stream(stream: Pin<&mut S>, cx: &mut Context<'_>) -> Poll>> where S: Stream>, { diff --git a/muxers/mplex/src/lib.rs b/muxers/mplex/src/lib.rs index 812aab03..dd45e1f7 100644 --- a/muxers/mplex/src/lib.rs +++ b/muxers/mplex/src/lib.rs @@ -245,7 +245,7 @@ impl ArcWake for Notifier { /// /// If `Pending` is returned, the waker is kept and notified later, just like with any `Poll`. /// `Ready(Ok())` is almost always returned. An error is returned if the stream is EOF. -fn next_match(inner: &mut MultiplexInner, cx: &mut Context, mut filter: F) -> Poll> +fn next_match(inner: &mut MultiplexInner, cx: &mut Context<'_>, mut filter: F) -> Poll> where C: AsyncRead + AsyncWrite + Unpin, F: FnMut(&codec::Elem) -> Option, { @@ -324,7 +324,7 @@ where C: AsyncRead + AsyncWrite + Unpin, } // Small convenience function that tries to write `elem` to the stream. -fn poll_send(inner: &mut MultiplexInner, cx: &mut Context, elem: codec::Elem) -> Poll> +fn poll_send(inner: &mut MultiplexInner, cx: &mut Context<'_>, elem: codec::Elem) -> Poll> where C: AsyncRead + AsyncWrite + Unpin { ensure_no_error_no_close(inner)?; @@ -366,7 +366,7 @@ where C: AsyncRead + AsyncWrite + Unpin type OutboundSubstream = OutboundSubstream; type Error = IoError; - fn poll_event(&self, cx: &mut Context) -> Poll, IoError>> { + fn poll_event(&self, cx: &mut Context<'_>) -> Poll, IoError>> { let mut inner = self.inner.lock(); if inner.opened_substreams.len() >= inner.config.max_substreams { @@ -416,7 +416,7 @@ where C: AsyncRead + AsyncWrite + Unpin } } - fn poll_outbound(&self, cx: &mut Context, substream: &mut Self::OutboundSubstream) -> Poll> { + fn poll_outbound(&self, cx: &mut Context<'_>, substream: &mut Self::OutboundSubstream) -> Poll> { loop { let mut inner = self.inner.lock(); @@ -475,7 +475,7 @@ where C: AsyncRead + AsyncWrite + Unpin // Nothing to do. } - fn read_substream(&self, cx: &mut Context, substream: &mut Self::Substream, buf: &mut [u8]) -> Poll> { + fn read_substream(&self, cx: &mut Context<'_>, substream: &mut Self::Substream, buf: &mut [u8]) -> Poll> { loop { // First, transfer from `current_data`. if !substream.current_data.is_empty() { @@ -529,7 +529,7 @@ where C: AsyncRead + AsyncWrite + Unpin } } - fn write_substream(&self, cx: &mut Context, substream: &mut Self::Substream, buf: &[u8]) -> Poll> { + fn write_substream(&self, cx: &mut Context<'_>, substream: &mut Self::Substream, buf: &[u8]) -> Poll> { if !substream.local_open { return Poll::Ready(Err(IoErrorKind::BrokenPipe.into())); } @@ -551,7 +551,7 @@ where C: AsyncRead + AsyncWrite + Unpin } } - fn flush_substream(&self, cx: &mut Context, _substream: &mut Self::Substream) -> Poll> { + fn flush_substream(&self, cx: &mut Context<'_>, _substream: &mut Self::Substream) -> Poll> { let mut inner = self.inner.lock(); ensure_no_error_no_close(&mut inner)?; let inner = &mut *inner; // Avoids borrow errors @@ -563,7 +563,7 @@ where C: AsyncRead + AsyncWrite + Unpin result } - fn shutdown_substream(&self, cx: &mut Context, sub: &mut Self::Substream) -> Poll> { + fn shutdown_substream(&self, cx: &mut Context<'_>, sub: &mut Self::Substream) -> Poll> { if !sub.local_open { return Poll::Ready(Ok(())); } @@ -587,7 +587,7 @@ where C: AsyncRead + AsyncWrite + Unpin }) } - fn close(&self, cx: &mut Context) -> Poll> { + fn close(&self, cx: &mut Context<'_>) -> Poll> { let inner = &mut *self.inner.lock(); if inner.is_shutdown { return Poll::Ready(Ok(())) @@ -609,7 +609,7 @@ where C: AsyncRead + AsyncWrite + Unpin } } - fn flush_all(&self, cx: &mut Context) -> Poll> { + fn flush_all(&self, cx: &mut Context<'_>) -> Poll> { let inner = &mut *self.inner.lock(); if inner.is_shutdown { return Poll::Ready(Ok(())) diff --git a/muxers/yamux/src/lib.rs b/muxers/yamux/src/lib.rs index 13143abe..6d510997 100644 --- a/muxers/yamux/src/lib.rs +++ b/muxers/yamux/src/lib.rs @@ -37,7 +37,7 @@ pub use yamux::WindowUpdateMode; pub struct Yamux(Mutex>); impl fmt::Debug for Yamux { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Yamux") } } @@ -103,7 +103,7 @@ where type OutboundSubstream = OpenSubstreamToken; type Error = YamuxError; - fn poll_event(&self, c: &mut Context) -> Poll> { + fn poll_event(&self, c: &mut Context<'_>) -> Poll> { let mut inner = self.0.lock(); match ready!(inner.incoming.poll_next_unpin(c)) { Some(Ok(s)) => Poll::Ready(Ok(StreamMuxerEvent::InboundSubstream(s))), @@ -116,7 +116,7 @@ where OpenSubstreamToken(()) } - fn poll_outbound(&self, c: &mut Context, _: &mut OpenSubstreamToken) -> Poll { + fn poll_outbound(&self, c: &mut Context<'_>, _: &mut OpenSubstreamToken) -> Poll { let mut inner = self.0.lock(); Pin::new(&mut inner.control).poll_open_stream(c).map_err(YamuxError) } @@ -125,25 +125,25 @@ where self.0.lock().control.abort_open_stream() } - fn read_substream(&self, c: &mut Context, s: &mut Self::Substream, b: &mut [u8]) -> Poll { + fn read_substream(&self, c: &mut Context<'_>, s: &mut Self::Substream, b: &mut [u8]) -> Poll { Pin::new(s).poll_read(c, b).map_err(|e| YamuxError(e.into())) } - fn write_substream(&self, c: &mut Context, s: &mut Self::Substream, b: &[u8]) -> Poll { + fn write_substream(&self, c: &mut Context<'_>, s: &mut Self::Substream, b: &[u8]) -> Poll { Pin::new(s).poll_write(c, b).map_err(|e| YamuxError(e.into())) } - fn flush_substream(&self, c: &mut Context, s: &mut Self::Substream) -> Poll<()> { + fn flush_substream(&self, c: &mut Context<'_>, s: &mut Self::Substream) -> Poll<()> { Pin::new(s).poll_flush(c).map_err(|e| YamuxError(e.into())) } - fn shutdown_substream(&self, c: &mut Context, s: &mut Self::Substream) -> Poll<()> { + fn shutdown_substream(&self, c: &mut Context<'_>, s: &mut Self::Substream) -> Poll<()> { Pin::new(s).poll_close(c).map_err(|e| YamuxError(e.into())) } fn destroy_substream(&self, _: Self::Substream) { } - fn close(&self, c: &mut Context) -> Poll<()> { + fn close(&self, c: &mut Context<'_>) -> Poll<()> { let mut inner = self.0.lock(); if let std::task::Poll::Ready(x) = Pin::new(&mut inner.control).poll_close(c) { return Poll::Ready(x.map_err(YamuxError)) @@ -158,7 +158,7 @@ where Poll::Pending } - fn flush_all(&self, _: &mut Context) -> Poll<()> { + fn flush_all(&self, _: &mut Context<'_>) -> Poll<()> { Poll::Ready(Ok(())) } } @@ -290,7 +290,7 @@ pub struct Incoming { } impl fmt::Debug for Incoming { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Incoming") } } @@ -302,7 +302,7 @@ pub struct LocalIncoming { } impl fmt::Debug for LocalIncoming { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("LocalIncoming") } } @@ -310,7 +310,7 @@ impl fmt::Debug for LocalIncoming { impl Stream for Incoming { type Item = Result; - fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> std::task::Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> std::task::Poll> { self.stream.as_mut().poll_next_unpin(cx) } @@ -325,7 +325,7 @@ impl Unpin for Incoming { impl Stream for LocalIncoming { type Item = Result; - fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> std::task::Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> std::task::Poll> { self.stream.as_mut().poll_next_unpin(cx) } diff --git a/protocols/deflate/src/lib.rs b/protocols/deflate/src/lib.rs index 32a82f24..6ec576d8 100644 --- a/protocols/deflate/src/lib.rs +++ b/protocols/deflate/src/lib.rs @@ -104,7 +104,7 @@ impl DeflateOutput { /// Tries to write the content of `self.write_out` to `self.inner`. /// Returns `Ready(Ok(()))` if `self.write_out` is empty. - fn flush_write_out(&mut self, cx: &mut Context) -> Poll> + fn flush_write_out(&mut self, cx: &mut Context<'_>) -> Poll> where S: AsyncWrite + Unpin { loop { @@ -125,7 +125,7 @@ impl DeflateOutput { impl AsyncRead for DeflateOutput where S: AsyncRead + Unpin { - 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> { // We use a `this` variable because the compiler doesn't allow multiple mutable borrows // across a `Deref`. let this = &mut *self; @@ -177,7 +177,7 @@ impl AsyncRead for DeflateOutput impl AsyncWrite for DeflateOutput where S: AsyncWrite + Unpin { - fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) + fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { // We use a `this` variable because the compiler doesn't allow multiple mutable borrows @@ -208,7 +208,7 @@ impl AsyncWrite for DeflateOutput } } - fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { // We use a `this` variable because the compiler doesn't allow multiple mutable borrows // across a `Deref`. let this = &mut *self; @@ -231,7 +231,7 @@ impl AsyncWrite for DeflateOutput AsyncWrite::poll_flush(Pin::new(&mut this.inner), 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> { // We use a `this` variable because the compiler doesn't allow multiple mutable borrows // across a `Deref`. let this = &mut *self; diff --git a/protocols/floodsub/src/layer.rs b/protocols/floodsub/src/layer.rs index c1d66572..c2ae8146 100644 --- a/protocols/floodsub/src/layer.rs +++ b/protocols/floodsub/src/layer.rs @@ -370,7 +370,7 @@ impl NetworkBehaviour for Floodsub { fn poll( &mut self, - _: &mut Context, + _: &mut Context<'_>, _: &mut impl PollParameters, ) -> Poll< NetworkBehaviourAction< diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index 2a17efaf..a959cad9 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -1133,7 +1133,7 @@ impl NetworkBehaviour for Gossipsub { fn poll( &mut self, - cx: &mut Context, + cx: &mut Context<'_>, _: &mut impl PollParameters, ) -> Poll< NetworkBehaviourAction< diff --git a/protocols/gossipsub/src/config.rs b/protocols/gossipsub/src/config.rs index 5a715848..a01895ef 100644 --- a/protocols/gossipsub/src/config.rs +++ b/protocols/gossipsub/src/config.rs @@ -230,7 +230,7 @@ impl GossipsubConfigBuilder { } impl std::fmt::Debug for GossipsubConfig { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut builder = f.debug_struct("GossipsubConfig"); let _ = builder.field("protocol_id", &self.protocol_id); let _ = builder.field("history_length", &self.history_length); diff --git a/protocols/gossipsub/src/handler.rs b/protocols/gossipsub/src/handler.rs index b9cf9559..41f146d1 100644 --- a/protocols/gossipsub/src/handler.rs +++ b/protocols/gossipsub/src/handler.rs @@ -165,7 +165,7 @@ impl ProtocolsHandler for GossipsubHandler { fn poll( &mut self, - cx: &mut Context, + cx: &mut Context<'_>, ) -> Poll< ProtocolsHandlerEvent< Self::OutboundProtocol, diff --git a/protocols/gossipsub/src/mcache.rs b/protocols/gossipsub/src/mcache.rs index 8e74308c..6c284ae7 100644 --- a/protocols/gossipsub/src/mcache.rs +++ b/protocols/gossipsub/src/mcache.rs @@ -18,7 +18,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -extern crate fnv; + use crate::protocol::{GossipsubMessage, MessageId}; use crate::topic::TopicHash; diff --git a/protocols/gossipsub/src/topic.rs b/protocols/gossipsub/src/topic.rs index 6eacb9b3..09d3f578 100644 --- a/protocols/gossipsub/src/topic.rs +++ b/protocols/gossipsub/src/topic.rs @@ -81,13 +81,13 @@ impl Topic { } impl fmt::Display for Topic { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.topic) } } impl fmt::Display for TopicHash { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.hash) } } diff --git a/protocols/gossipsub/tests/smoke.rs b/protocols/gossipsub/tests/smoke.rs index f16486e6..136481f3 100644 --- a/protocols/gossipsub/tests/smoke.rs +++ b/protocols/gossipsub/tests/smoke.rs @@ -50,7 +50,7 @@ struct Graph { impl Future for Graph { type Output = (Multiaddr, GossipsubEvent); - fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { for (addr, node) in &mut self.nodes { match node.poll_next_unpin(cx) { Poll::Ready(Some(event)) => return Poll::Ready((addr.clone(), event)), diff --git a/protocols/identify/src/handler.rs b/protocols/identify/src/handler.rs index 1d24cb71..0a9b341d 100644 --- a/protocols/identify/src/handler.rs +++ b/protocols/identify/src/handler.rs @@ -132,7 +132,7 @@ impl ProtocolsHandler for IdentifyHandler { self.keep_alive } - fn poll(&mut self, cx: &mut Context) -> Poll< + fn poll(&mut self, cx: &mut Context<'_>) -> Poll< ProtocolsHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, diff --git a/protocols/identify/src/identify.rs b/protocols/identify/src/identify.rs index 312e273d..dbaf2c07 100644 --- a/protocols/identify/src/identify.rs +++ b/protocols/identify/src/identify.rs @@ -167,7 +167,7 @@ impl NetworkBehaviour for Identify { fn poll( &mut self, - cx: &mut Context, + cx: &mut Context<'_>, params: &mut impl PollParameters, ) -> Poll< NetworkBehaviourAction< diff --git a/protocols/kad/src/addresses.rs b/protocols/kad/src/addresses.rs index 4c894a40..5105802c 100644 --- a/protocols/kad/src/addresses.rs +++ b/protocols/kad/src/addresses.rs @@ -94,7 +94,7 @@ impl Addresses { } impl fmt::Debug for Addresses { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list() .entries(self.addrs.iter()) .finish() diff --git a/protocols/kad/src/behaviour.rs b/protocols/kad/src/behaviour.rs index 8fd60e6d..0349ee67 100644 --- a/protocols/kad/src/behaviour.rs +++ b/protocols/kad/src/behaviour.rs @@ -531,7 +531,7 @@ where /// Returns an iterator over all non-empty buckets in the routing table. pub fn kbuckets(&mut self) - -> impl Iterator, Addresses>> + -> impl Iterator, Addresses>> { self.kbuckets.iter().filter(|b| !b.is_empty()) } @@ -540,7 +540,7 @@ where /// /// Returns `None` if the given key refers to the local key. pub fn kbucket(&mut self, key: K) - -> Option, Addresses>> + -> Option, Addresses>> where K: Borrow<[u8]> + Clone { @@ -1693,7 +1693,7 @@ where }; } - fn poll(&mut self, cx: &mut Context, parameters: &mut impl PollParameters) -> Poll< + fn poll(&mut self, cx: &mut Context<'_>, parameters: &mut impl PollParameters) -> Poll< NetworkBehaviourAction< as ProtocolsHandler>::InEvent, Self::OutEvent, diff --git a/protocols/kad/src/handler.rs b/protocols/kad/src/handler.rs index 8c08e90e..3d4e6cef 100644 --- a/protocols/kad/src/handler.rs +++ b/protocols/kad/src/handler.rs @@ -109,7 +109,7 @@ impl SubstreamState { /// Tries to close the substream. /// /// If the substream is not ready to be closed, returns it back. - fn try_close(&mut self, cx: &mut Context) -> Poll<()> { + fn try_close(&mut self, cx: &mut Context<'_>) -> Poll<()> { match self { SubstreamState::OutPendingOpen(_, _) | SubstreamState::OutReportError(_, _) => Poll::Ready(()), @@ -612,7 +612,7 @@ where fn poll( &mut self, - cx: &mut Context, + cx: &mut Context<'_>, ) -> Poll< ProtocolsHandlerEvent, > { @@ -679,7 +679,7 @@ impl Default for KademliaHandlerConfig { fn advance_substream( state: SubstreamState, upgrade: KademliaProtocolConfig, - cx: &mut Context, + cx: &mut Context<'_>, ) -> ( Option>, Option< diff --git a/protocols/kad/src/jobs.rs b/protocols/kad/src/jobs.rs index f7a2cd4d..e1b49262 100644 --- a/protocols/kad/src/jobs.rs +++ b/protocols/kad/src/jobs.rs @@ -107,7 +107,7 @@ impl PeriodicJob { /// Returns `true` if the job is currently not running but ready /// to be run, `false` otherwise. - fn is_ready(&mut self, cx: &mut Context, now: Instant) -> bool { + fn is_ready(&mut self, cx: &mut Context<'_>, now: Instant) -> bool { if let PeriodicJobState::Waiting(delay, deadline) = &mut self.state { if now >= *deadline || !Future::poll(Pin::new(delay), cx).is_pending() { return true @@ -190,7 +190,7 @@ impl PutRecordJob { /// Must be called in the context of a task. When `NotReady` is returned, /// the current task is registered to be notified when the job is ready /// to be run. - pub fn poll(&mut self, cx: &mut Context, store: &mut T, now: Instant) -> Poll + pub fn poll(&mut self, cx: &mut Context<'_>, store: &mut T, now: Instant) -> Poll where for<'a> T: RecordStore<'a> { @@ -288,7 +288,7 @@ impl AddProviderJob { /// Must be called in the context of a task. When `NotReady` is returned, /// the current task is registered to be notified when the job is ready /// to be run. - pub fn poll(&mut self, cx: &mut Context, store: &mut T, now: Instant) -> Poll + pub fn poll(&mut self, cx: &mut Context<'_>, store: &mut T, now: Instant) -> Poll where for<'a> T: RecordStore<'a> { diff --git a/protocols/kad/src/query.rs b/protocols/kad/src/query.rs index 67d9fb58..fb52d8bc 100644 --- a/protocols/kad/src/query.rs +++ b/protocols/kad/src/query.rs @@ -162,7 +162,7 @@ impl QueryPool { } /// Polls the pool to advance the queries. - pub fn poll(&mut self, now: Instant) -> QueryPoolState { + pub fn poll(&mut self, now: Instant) -> QueryPoolState<'_, TInner> { let mut finished = None; let mut timeout = None; let mut waiting = None; @@ -327,7 +327,7 @@ impl Query { } /// Advances the state of the underlying peer iterator. - fn next(&mut self, now: Instant) -> PeersIterState { + fn next(&mut self, now: Instant) -> PeersIterState<'_> { let state = match &mut self.peer_iter { QueryPeerIter::Closest(iter) => iter.next(now), QueryPeerIter::ClosestDisjoint(iter) => iter.next(now), diff --git a/protocols/kad/src/query/peers/closest.rs b/protocols/kad/src/query/peers/closest.rs index 7b751a4f..6f3c4eea 100644 --- a/protocols/kad/src/query/peers/closest.rs +++ b/protocols/kad/src/query/peers/closest.rs @@ -267,7 +267,7 @@ impl ClosestPeersIter { } /// Advances the state of the iterator, potentially getting a new peer to contact. - pub fn next(&mut self, now: Instant) -> PeersIterState { + pub fn next(&mut self, now: Instant) -> PeersIterState<'_> { if let State::Finished = self.state { return PeersIterState::Finished } diff --git a/protocols/kad/src/query/peers/closest/disjoint.rs b/protocols/kad/src/query/peers/closest/disjoint.rs index 480000fe..0bc176a8 100644 --- a/protocols/kad/src/query/peers/closest/disjoint.rs +++ b/protocols/kad/src/query/peers/closest/disjoint.rs @@ -181,7 +181,7 @@ impl ClosestDisjointPeersIter { self.iters.iter().any(|i| i.is_waiting(peer)) } - pub fn next(&mut self, now: Instant) -> PeersIterState { + pub fn next(&mut self, now: Instant) -> PeersIterState<'_> { let mut state = None; // Ensure querying each iterator at most once. @@ -713,7 +713,7 @@ mod tests { struct Graph(HashMap); impl std::fmt::Debug for Graph { - fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fmt.debug_list().entries(self.0.iter().map(|(id, _)| id)).finish() } } @@ -807,7 +807,7 @@ mod tests { } impl PeerIterator { - fn next(&mut self, now: Instant) -> PeersIterState { + fn next(&mut self, now: Instant) -> PeersIterState<'_> { match self { PeerIterator::Disjoint(iter) => iter.next(now), PeerIterator::Closest(iter) => iter.next(now), diff --git a/protocols/kad/src/query/peers/fixed.rs b/protocols/kad/src/query/peers/fixed.rs index 723ce414..ba4de596 100644 --- a/protocols/kad/src/query/peers/fixed.rs +++ b/protocols/kad/src/query/peers/fixed.rs @@ -129,7 +129,7 @@ impl FixedPeersIter { self.state == State::Finished } - pub fn next(&mut self) -> PeersIterState { + pub fn next(&mut self) -> PeersIterState<'_> { match &mut self.state { State::Finished => return PeersIterState::Finished, State::Waiting { num_waiting } => { diff --git a/protocols/kad/src/record/store.rs b/protocols/kad/src/record/store.rs index c050b35e..82402ed3 100644 --- a/protocols/kad/src/record/store.rs +++ b/protocols/kad/src/record/store.rs @@ -64,7 +64,7 @@ pub trait RecordStore<'a> { type ProvidedIter: Iterator>; /// Gets a record from the store, given its key. - fn get(&'a self, k: &Key) -> Option>; + fn get(&'a self, k: &Key) -> Option>; /// Puts a record into the store. fn put(&'a mut self, r: Record) -> Result<()>; diff --git a/protocols/kad/src/record/store/memory.rs b/protocols/kad/src/record/store/memory.rs index fe7ef5f9..e0a2e1d2 100644 --- a/protocols/kad/src/record/store/memory.rs +++ b/protocols/kad/src/record/store/memory.rs @@ -106,7 +106,7 @@ impl<'a> RecordStore<'a> for MemoryStore { fn(&'a ProviderRecord) -> Cow<'a, ProviderRecord> >; - fn get(&'a self, k: &Key) -> Option> { + fn get(&'a self, k: &Key) -> Option> { self.records.get(k).map(Cow::Borrowed) } diff --git a/protocols/mdns/src/behaviour.rs b/protocols/mdns/src/behaviour.rs index abc580ff..abdd4d44 100644 --- a/protocols/mdns/src/behaviour.rs +++ b/protocols/mdns/src/behaviour.rs @@ -213,7 +213,7 @@ impl NetworkBehaviour for Mdns { fn poll( &mut self, - cx: &mut Context, + cx: &mut Context<'_>, params: &mut impl PollParameters, ) -> Poll< NetworkBehaviourAction< diff --git a/protocols/mdns/src/service.rs b/protocols/mdns/src/service.rs index 3f8f3dfc..45b1132f 100644 --- a/protocols/mdns/src/service.rs +++ b/protocols/mdns/src/service.rs @@ -397,7 +397,7 @@ pub struct MdnsResponse { impl MdnsResponse { /// Creates a new `MdnsResponse` based on the provided `Packet`. - fn new(packet: Packet, from: SocketAddr) -> MdnsResponse { + fn new(packet: Packet<'_>, from: SocketAddr) -> MdnsResponse { let peers = packet.answers.iter().filter_map(|record| { if record.name.to_string().as_bytes() != SERVICE_NAME { return None; @@ -471,7 +471,7 @@ pub struct MdnsPeer { impl MdnsPeer { /// Creates a new `MdnsPeer` based on the provided `Packet`. - pub fn new(packet: &Packet, record_value: String, my_peer_id: PeerId, ttl: u32) -> MdnsPeer { + pub fn new(packet: &Packet<'_>, record_value: String, my_peer_id: PeerId, ttl: u32) -> MdnsPeer { let addrs = packet .additional .iter() diff --git a/protocols/noise/src/io.rs b/protocols/noise/src/io.rs index 751280a6..992988e9 100644 --- a/protocols/noise/src/io.rs +++ b/protocols/noise/src/io.rs @@ -62,7 +62,7 @@ impl NoiseOutput { } impl AsyncRead for NoiseOutput { - 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> { loop { let len = self.recv_buffer.len(); let off = self.recv_offset; @@ -94,7 +94,7 @@ impl AsyncRead for NoiseOutput { } impl AsyncWrite for NoiseOutput { - 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> { let this = Pin::into_inner(self); let mut io = Pin::new(&mut this.io); let frame_buf = &mut this.send_buffer; @@ -118,7 +118,7 @@ impl AsyncWrite for NoiseOutput { return Poll::Ready(Ok(n)) } - fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = Pin::into_inner(self); let mut io = Pin::new(&mut this.io); let frame_buf = &mut this.send_buffer; @@ -134,7 +134,7 @@ impl AsyncWrite for NoiseOutput { io.as_mut().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().poll_flush(cx))?; Pin::new(&mut self.io).poll_close(cx) } diff --git a/protocols/noise/src/io/framed.rs b/protocols/noise/src/io/framed.rs index ce0a8269..156703de 100644 --- a/protocols/noise/src/io/framed.rs +++ b/protocols/noise/src/io/framed.rs @@ -164,7 +164,7 @@ where { type Item = io::Result; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let mut this = Pin::into_inner(self); loop { trace!("read state: {:?}", this.read_state); @@ -253,7 +253,7 @@ where { type Error = io::Error; - fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let mut this = Pin::into_inner(self); loop { trace!("write state {:?}", this.write_state); @@ -334,12 +334,12 @@ where } } - 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_ready(cx))?; Pin::new(&mut self.io).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().poll_flush(cx))?; Pin::new(&mut self.io).poll_close(cx) } diff --git a/protocols/ping/src/handler.rs b/protocols/ping/src/handler.rs index a2ab5316..78aa6453 100644 --- a/protocols/ping/src/handler.rs +++ b/protocols/ping/src/handler.rs @@ -136,7 +136,7 @@ pub enum PingFailure { } impl fmt::Display for PingFailure { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { PingFailure::Timeout => f.write_str("Ping timeout"), PingFailure::Other { error } => write!(f, "Ping error: {}", error) @@ -221,7 +221,7 @@ impl ProtocolsHandler for PingHandler { } } - fn poll(&mut self, cx: &mut Context) -> Poll> { + fn poll(&mut self, cx: &mut Context<'_>) -> Poll> { if let Some(result) = self.pending_results.pop_back() { if let Ok(PingSuccess::Ping { .. }) = result { self.failures = 0; diff --git a/protocols/ping/src/lib.rs b/protocols/ping/src/lib.rs index 82b828ad..386465e1 100644 --- a/protocols/ping/src/lib.rs +++ b/protocols/ping/src/lib.rs @@ -108,7 +108,7 @@ impl NetworkBehaviour for Ping { self.events.push_front(PingEvent { peer, result }) } - fn poll(&mut self, _: &mut Context, _: &mut impl PollParameters) + fn poll(&mut self, _: &mut Context<'_>, _: &mut impl PollParameters) -> Poll> { if let Some(e) = self.events.pop_back() { diff --git a/protocols/plaintext/src/lib.rs b/protocols/plaintext/src/lib.rs index daa6f4c7..c1cb8fe7 100644 --- a/protocols/plaintext/src/lib.rs +++ b/protocols/plaintext/src/lib.rs @@ -192,7 +192,7 @@ where { 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> { Sink::poll_ready(Pin::new(&mut self.inner), cx) } @@ -200,11 +200,11 @@ where Sink::start_send(Pin::new(&mut self.inner), 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> { Sink::poll_flush(Pin::new(&mut self.inner), 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> { Sink::poll_close(Pin::new(&mut self.inner), cx) } } @@ -232,7 +232,7 @@ where } impl AsyncRead for PlainTextOutput { - fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) + fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll> { AsyncRead::poll_read(Pin::new(&mut self.stream), cx, buf) @@ -240,19 +240,19 @@ impl AsyncRead for PlainTextOutput { } impl AsyncWrite for PlainTextOutput { - fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) + fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { AsyncWrite::poll_write(Pin::new(&mut self.stream), cx, buf) } - fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { AsyncWrite::poll_flush(Pin::new(&mut self.stream), cx) } - fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { AsyncWrite::poll_close(Pin::new(&mut self.stream), cx) diff --git a/protocols/pnet/src/lib.rs b/protocols/pnet/src/lib.rs index 496cd7d6..e4715342 100644 --- a/protocols/pnet/src/lib.rs +++ b/protocols/pnet/src/lib.rs @@ -243,7 +243,7 @@ impl PnetOutput { impl AsyncRead for PnetOutput { fn poll_read( self: Pin<&mut Self>, - cx: &mut Context, + cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll> { let this = self.project(); @@ -260,17 +260,17 @@ impl AsyncRead for PnetOutput { impl AsyncWrite for PnetOutput { fn poll_write( self: Pin<&mut Self>, - cx: &mut Context, + cx: &mut Context<'_>, buf: &[u8], ) -> Poll> { self.project().inner.poll_write(cx, buf) } - fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.project().inner.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.project().inner.poll_close(cx) } } diff --git a/protocols/request-response/src/handler.rs b/protocols/request-response/src/handler.rs index 3a491a69..17eff4db 100644 --- a/protocols/request-response/src/handler.rs +++ b/protocols/request-response/src/handler.rs @@ -258,7 +258,7 @@ where fn poll( &mut self, - cx: &mut Context, + cx: &mut Context<'_>, ) -> Poll< ProtocolsHandlerEvent, RequestId, Self::OutEvent, Self::Error>, > { diff --git a/protocols/request-response/src/lib.rs b/protocols/request-response/src/lib.rs index c2192934..25b69d7a 100644 --- a/protocols/request-response/src/lib.rs +++ b/protocols/request-response/src/lib.rs @@ -577,7 +577,7 @@ where } } - fn poll(&mut self, _: &mut Context, _: &mut impl PollParameters) + fn poll(&mut self, _: &mut Context<'_>, _: &mut impl PollParameters) -> Poll, RequestResponseEvent diff --git a/protocols/secio/src/codec/decode.rs b/protocols/secio/src/codec/decode.rs index 04bbad56..8ea0cd4e 100644 --- a/protocols/secio/src/codec/decode.rs +++ b/protocols/secio/src/codec/decode.rs @@ -66,7 +66,7 @@ where { type Item = Result, SecioError>; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.project(); let frame = match TryStream::try_poll_next(this.raw_stream, cx) { @@ -114,7 +114,7 @@ where { type Error = S::Error; - fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.project(); Sink::poll_ready(this.raw_stream, cx) } @@ -124,12 +124,12 @@ where Sink::start_send(this.raw_stream, item) } - fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.project(); Sink::poll_flush(this.raw_stream, cx) } - fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.project(); Sink::poll_close(this.raw_stream, cx) } diff --git a/protocols/secio/src/codec/encode.rs b/protocols/secio/src/codec/encode.rs index 88611bc1..c4bbf5ac 100644 --- a/protocols/secio/src/codec/encode.rs +++ b/protocols/secio/src/codec/encode.rs @@ -55,7 +55,7 @@ where { type Error = S::Error; - fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.project(); Sink::poll_ready(this.raw_sink, cx) } @@ -69,12 +69,12 @@ where Sink::start_send(this.raw_sink, data_buf) } - fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.project(); Sink::poll_flush(this.raw_sink, cx) } - fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.project(); Sink::poll_close(this.raw_sink, cx) } @@ -86,7 +86,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> { let this = self.project(); Stream::poll_next(this.raw_sink, cx) } diff --git a/protocols/secio/src/codec/len_prefix.rs b/protocols/secio/src/codec/len_prefix.rs index 8b70083b..18882026 100644 --- a/protocols/secio/src/codec/len_prefix.rs +++ b/protocols/secio/src/codec/len_prefix.rs @@ -30,7 +30,7 @@ pub struct LenPrefixCodec { } impl fmt::Debug for LenPrefixCodec { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("LenPrefixCodec") } } @@ -95,7 +95,7 @@ where { type Item = io::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.stream.poll_next_unpin(cx) } } @@ -106,7 +106,7 @@ where { 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> { Pin::new(&mut self.sink).poll_ready(cx) } @@ -114,11 +114,11 @@ where Pin::new(&mut self.sink).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.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> { Pin::new(&mut self.sink).poll_close(cx) } } diff --git a/protocols/secio/src/lib.rs b/protocols/secio/src/lib.rs index 8c067f6b..7332c725 100644 --- a/protocols/secio/src/lib.rs +++ b/protocols/secio/src/lib.rs @@ -206,7 +206,7 @@ impl AsyncRead for SecioOutput where S: AsyncRead + AsyncWrite + Unpin + Send + 'static { - fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) + fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll> { AsyncRead::poll_read(Pin::new(&mut self.stream), cx, buf) @@ -217,19 +217,19 @@ impl AsyncWrite for SecioOutput where S: AsyncRead + AsyncWrite + Unpin + Send + 'static { - fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) + fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { AsyncWrite::poll_write(Pin::new(&mut self.stream), cx, buf) } - fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { AsyncWrite::poll_flush(Pin::new(&mut self.stream), cx) } - fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) + fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { AsyncWrite::poll_close(Pin::new(&mut self.stream), cx) @@ -273,7 +273,7 @@ where { 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> { Sink::poll_ready(Pin::new(&mut self.inner), cx) } @@ -281,11 +281,11 @@ where Sink::start_send(Pin::new(&mut self.inner), 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> { Sink::poll_flush(Pin::new(&mut self.inner), 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> { Sink::poll_close(Pin::new(&mut self.inner), cx) } } @@ -296,7 +296,7 @@ where { type Item = Result, SecioError>; - fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { Stream::poll_next(Pin::new(&mut self.inner), cx) } } diff --git a/src/bandwidth.rs b/src/bandwidth.rs index ca067b4d..705164b5 100644 --- a/src/bandwidth.rs +++ b/src/bandwidth.rs @@ -91,7 +91,7 @@ where { type Item = Result, TErr>, TErr>; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.project(); let event = @@ -122,7 +122,7 @@ pub struct BandwidthFuture { impl Future for BandwidthFuture { type Output = Result, TInner::Error>; - fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let this = self.project(); let inner = ready!(this.inner.try_poll(cx)?); let logged = BandwidthConnecLogging { inner, sinks: this.sinks.clone() }; @@ -165,14 +165,14 @@ pub struct BandwidthConnecLogging { } impl AsyncRead for BandwidthConnecLogging { - 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> { let this = self.project(); let num_bytes = ready!(this.inner.poll_read(cx, buf))?; this.sinks.inbound.fetch_add(u64::try_from(num_bytes).unwrap_or(u64::max_value()), Ordering::Relaxed); Poll::Ready(Ok(num_bytes)) } - 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> { let this = self.project(); let num_bytes = ready!(this.inner.poll_read_vectored(cx, bufs))?; this.sinks.inbound.fetch_add(u64::try_from(num_bytes).unwrap_or(u64::max_value()), Ordering::Relaxed); @@ -181,26 +181,26 @@ impl AsyncRead for BandwidthConnecLogging { } impl AsyncWrite for BandwidthConnecLogging { - 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> { let this = self.project(); let num_bytes = ready!(this.inner.poll_write(cx, buf))?; this.sinks.outbound.fetch_add(u64::try_from(num_bytes).unwrap_or(u64::max_value()), Ordering::Relaxed); Poll::Ready(Ok(num_bytes)) } - 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> { let this = self.project(); let num_bytes = ready!(this.inner.poll_write_vectored(cx, bufs))?; this.sinks.outbound.fetch_add(u64::try_from(num_bytes).unwrap_or(u64::max_value()), Ordering::Relaxed); Poll::Ready(Ok(num_bytes)) } - fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.project(); this.inner.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> { let this = self.project(); this.inner.poll_close(cx) } diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index f75a31ab..93d2df09 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -171,7 +171,7 @@ pub trait NetworkBehaviour: Send + 'static { /// /// This API mimics the API of the `Stream` trait. The method may register the current task in /// order to wake it up at a later point in time. - fn poll(&mut self, cx: &mut Context, params: &mut impl PollParameters) + fn poll(&mut self, cx: &mut Context<'_>, params: &mut impl PollParameters) -> Poll::Handler as ProtocolsHandler>::InEvent, Self::OutEvent>>; } diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 800dbc13..84e69183 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -481,7 +481,7 @@ where TBehaviour: NetworkBehaviour, /// Internal function used by everything event-related. /// /// Polls the `Swarm` for the next event. - fn poll_next_event(mut self: Pin<&mut Self>, cx: &mut Context) + fn poll_next_event(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { // We use a `this` variable because the compiler can't mutably borrow multiple times @@ -779,7 +779,7 @@ enum PendingNotifyHandler { fn notify_one<'a, TInEvent, TConnInfo, TPeerId>( conn: &mut EstablishedConnection<'a, TInEvent, TConnInfo, TPeerId>, event: TInEvent, - cx: &mut Context, + cx: &mut Context<'_>, ) -> Option where TPeerId: Eq + std::hash::Hash + Clone, @@ -810,7 +810,7 @@ fn notify_any<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>( ids: SmallVec<[ConnectionId; 10]>, peer: &mut ConnectedPeer<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>, event: TInEvent, - cx: &mut Context, + cx: &mut Context<'_>, ) -> Option<(TInEvent, SmallVec<[ConnectionId; 10]>)> where TTrans: Transport, @@ -859,7 +859,7 @@ fn notify_all<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>( ids: SmallVec<[ConnectionId; 10]>, peer: &mut ConnectedPeer<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>, event: TInEvent, - cx: &mut Context, + cx: &mut Context<'_>, ) -> Option<(TInEvent, SmallVec<[ConnectionId; 10]>)> where TTrans: Transport, @@ -907,7 +907,7 @@ where TBehaviour: NetworkBehaviour, { type Item = TBehaviour::OutEvent; - 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 { let event = futures::ready!(ExpandedSwarm::poll_next_event(self.as_mut(), cx)); if let SwarmEvent::Behaviour(event) = event { @@ -1178,7 +1178,7 @@ impl NetworkBehaviour for DummyBehaviour { fn inject_event(&mut self, _: PeerId, _: ConnectionId, _: ::OutEvent) {} - fn poll(&mut self, _: &mut Context, _: &mut impl PollParameters) -> + fn poll(&mut self, _: &mut Context<'_>, _: &mut impl PollParameters) -> Poll::InEvent, Self::OutEvent>> { diff --git a/swarm/src/protocols_handler.rs b/swarm/src/protocols_handler.rs index 9721e9db..a994cadf 100644 --- a/swarm/src/protocols_handler.rs +++ b/swarm/src/protocols_handler.rs @@ -184,7 +184,7 @@ pub trait ProtocolsHandler: Send + 'static { fn connection_keep_alive(&self) -> KeepAlive; /// Should behave like `Stream::poll()`. - fn poll(&mut self, cx: &mut Context) -> Poll< + fn poll(&mut self, cx: &mut Context<'_>) -> Poll< ProtocolsHandlerEvent >; diff --git a/swarm/src/protocols_handler/dummy.rs b/swarm/src/protocols_handler/dummy.rs index fb2b781f..07047eb5 100644 --- a/swarm/src/protocols_handler/dummy.rs +++ b/swarm/src/protocols_handler/dummy.rs @@ -81,7 +81,7 @@ impl ProtocolsHandler for DummyProtocolsHandler { #[inline] fn poll( &mut self, - _: &mut Context, + _: &mut Context<'_>, ) -> Poll< ProtocolsHandlerEvent, > { diff --git a/swarm/src/protocols_handler/map_in.rs b/swarm/src/protocols_handler/map_in.rs index 46b54c7e..7a031022 100644 --- a/swarm/src/protocols_handler/map_in.rs +++ b/swarm/src/protocols_handler/map_in.rs @@ -104,7 +104,7 @@ where #[inline] fn poll( &mut self, - cx: &mut Context, + cx: &mut Context<'_>, ) -> Poll< ProtocolsHandlerEvent, > { diff --git a/swarm/src/protocols_handler/map_out.rs b/swarm/src/protocols_handler/map_out.rs index 67fe10f3..7b59fe73 100644 --- a/swarm/src/protocols_handler/map_out.rs +++ b/swarm/src/protocols_handler/map_out.rs @@ -100,7 +100,7 @@ where #[inline] fn poll( &mut self, - cx: &mut Context, + cx: &mut Context<'_>, ) -> Poll< ProtocolsHandlerEvent, > { diff --git a/swarm/src/protocols_handler/multi.rs b/swarm/src/protocols_handler/multi.rs index cfbc6a7b..a18e5026 100644 --- a/swarm/src/protocols_handler/multi.rs +++ b/swarm/src/protocols_handler/multi.rs @@ -58,7 +58,7 @@ where K: fmt::Debug + Eq + Hash, H: fmt::Debug { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("MultiHandler") .field("handlers", &self.handlers) .finish() @@ -154,7 +154,7 @@ where .unwrap_or(KeepAlive::No) } - fn poll(&mut self, cx: &mut Context) + fn poll(&mut self, cx: &mut Context<'_>) -> Poll> { // Calling `gen_range(0, 0)` (see below) would panic, so we have return early to avoid @@ -195,7 +195,7 @@ where K: fmt::Debug + Eq + Hash, H: fmt::Debug { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("IntoMultiHandler") .field("handlers", &self.handlers) .finish() @@ -266,7 +266,7 @@ where K: fmt::Debug + Eq + Hash, H: fmt::Debug { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Upgrade") .field("upgrades", &self.upgrades) .finish() @@ -369,7 +369,7 @@ impl DuplicateProtonameError { } impl fmt::Display for DuplicateProtonameError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Ok(s) = std::str::from_utf8(&self.0) { write!(f, "duplicate protocol name: {}", s) } else { diff --git a/swarm/src/protocols_handler/node_handler.rs b/swarm/src/protocols_handler/node_handler.rs index a24ea2cc..c11aa83a 100644 --- a/swarm/src/protocols_handler/node_handler.rs +++ b/swarm/src/protocols_handler/node_handler.rs @@ -225,7 +225,7 @@ where self.handler.inject_address_change(new_address); } - fn poll(&mut self, cx: &mut Context) -> Poll< + fn poll(&mut self, cx: &mut Context<'_>) -> Poll< Result, Self::Error> > { // Continue negotiation of newly-opened substreams on the listening side. diff --git a/swarm/src/protocols_handler/one_shot.rs b/swarm/src/protocols_handler/one_shot.rs index 4659fe0f..079cc815 100644 --- a/swarm/src/protocols_handler/one_shot.rs +++ b/swarm/src/protocols_handler/one_shot.rs @@ -191,7 +191,7 @@ where fn poll( &mut self, - _: &mut Context, + _: &mut Context<'_>, ) -> Poll< ProtocolsHandlerEvent, > { diff --git a/swarm/src/protocols_handler/select.rs b/swarm/src/protocols_handler/select.rs index 14f4dde7..32cd9ae3 100644 --- a/swarm/src/protocols_handler/select.rs +++ b/swarm/src/protocols_handler/select.rs @@ -187,7 +187,7 @@ where cmp::max(self.proto1.connection_keep_alive(), self.proto2.connection_keep_alive()) } - fn poll(&mut self, cx: &mut Context) -> Poll> { + fn poll(&mut self, cx: &mut Context<'_>) -> Poll> { match self.proto1.poll(cx) { Poll::Ready(ProtocolsHandlerEvent::Custom(event)) => { diff --git a/swarm/src/toggle.rs b/swarm/src/toggle.rs index 2ba58e95..efd61776 100644 --- a/swarm/src/toggle.rs +++ b/swarm/src/toggle.rs @@ -141,7 +141,7 @@ where } } - fn poll(&mut self, cx: &mut Context, params: &mut impl PollParameters) + fn poll(&mut self, cx: &mut Context<'_>, params: &mut impl PollParameters) -> Poll::Handler as ProtocolsHandler>::InEvent, Self::OutEvent>> { if let Some(inner) = self.inner.as_mut() { @@ -252,7 +252,7 @@ where fn poll( &mut self, - cx: &mut Context, + cx: &mut Context<'_>, ) -> Poll< ProtocolsHandlerEvent > { diff --git a/transports/tcp/src/lib.rs b/transports/tcp/src/lib.rs index 1e870f78..ee6bceb7 100644 --- a/transports/tcp/src/lib.rs +++ b/transports/tcp/src/lib.rs @@ -330,22 +330,22 @@ codegen!("tokio", TokioTcpConfig, TokioTcpTransStream, TokioTcpListenStream, app #[cfg(feature = "async-std")] impl AsyncRead for TcpTransStream { - 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> { AsyncRead::poll_read(Pin::new(&mut self.inner), cx, buf) } } #[cfg(feature = "async-std")] impl AsyncWrite for TcpTransStream { - 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> { AsyncWrite::poll_write(Pin::new(&mut self.inner), cx, buf) } - fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { AsyncWrite::poll_flush(Pin::new(&mut self.inner), 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> { AsyncWrite::poll_close(Pin::new(&mut self.inner), cx) } } diff --git a/transports/wasm-ext/src/lib.rs b/transports/wasm-ext/src/lib.rs index 2ce0f440..8c0e5012 100644 --- a/transports/wasm-ext/src/lib.rs +++ b/transports/wasm-ext/src/lib.rs @@ -151,7 +151,7 @@ impl ExtTransport { } impl fmt::Debug for ExtTransport { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("ExtTransport").finish() } } @@ -224,7 +224,7 @@ impl fmt::Debug for Dial { impl Future for Dial { 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 { match Future::poll(Pin::new(&mut *self.inner), cx) { Poll::Ready(Ok(connec)) => Poll::Ready(Ok(Connection::new(connec.into()))), Poll::Pending => Poll::Pending, @@ -253,7 +253,7 @@ impl fmt::Debug for Listen { impl Stream for Listen { type Item = Result>, JsErr>, JsErr>; - 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 let Some(ev) = self.pending_events.pop_front() { return Poll::Ready(Some(Ok(ev))); @@ -371,7 +371,7 @@ impl fmt::Debug for Connection { } impl AsyncRead for Connection { - 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> { loop { match mem::replace(&mut self.read_state, ConnectionReadState::Finished) { ConnectionReadState::Finished => break Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())), @@ -435,7 +435,7 @@ impl AsyncRead for Connection { } impl AsyncWrite for Connection { - 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> { // Note: as explained in the doc-comments of `Connection`, each call to this function must // map to exactly one call to `self.inner.write()`. @@ -457,12 +457,12 @@ impl AsyncWrite for Connection { Poll::Ready(Ok(buf.len())) } - fn poll_flush(self: Pin<&mut Self>, _: &mut Context) -> Poll> { + fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { // There's no flushing mechanism. In the FFI we consider that writing implicitly flushes. Poll::Ready(Ok(())) } - fn poll_close(self: Pin<&mut Self>, _: &mut Context) -> Poll> { + fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { // Shutting down is considered instantaneous. match self.inner.shutdown() { Ok(()) => Poll::Ready(Ok(())), diff --git a/transports/websocket/src/framed.rs b/transports/websocket/src/framed.rs index 4d2f9a7a..9f6d6efd 100644 --- a/transports/websocket/src/framed.rs +++ b/transports/websocket/src/framed.rs @@ -470,7 +470,7 @@ pub enum OutgoingData { } impl fmt::Debug for Connection { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Connection") } } @@ -547,7 +547,7 @@ where { type Item = io::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> { let item = ready!(self.receiver.poll_next_unpin(cx)); let item = item.map(|result| { result.map_err(|e| io::Error::new(io::ErrorKind::Other, e)) @@ -562,7 +562,7 @@ where { 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> { Pin::new(&mut self.sender) .poll_ready(cx) .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) @@ -574,13 +574,13 @@ where .map_err(|e| io::Error::new(io::ErrorKind::Other, 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> { Pin::new(&mut self.sender) .poll_flush(cx) .map_err(|e| io::Error::new(io::ErrorKind::Other, 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> { Pin::new(&mut self.sender) .poll_close(cx) .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) diff --git a/transports/websocket/src/lib.rs b/transports/websocket/src/lib.rs index 5327496d..10026a42 100644 --- a/transports/websocket/src/lib.rs +++ b/transports/websocket/src/lib.rs @@ -143,7 +143,7 @@ where { type Item = io::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> { loop { if let Some(item) = ready!(self.0.try_poll_next_unpin(cx)?) { if item.is_data() { @@ -162,7 +162,7 @@ where { 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> { Pin::new(&mut self.0).poll_ready(cx) } @@ -170,11 +170,11 @@ where Pin::new(&mut self.0).start_send(framed::OutgoingData::Binary(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.0).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.0).poll_close(cx) } } diff --git a/transports/websocket/src/tls.rs b/transports/websocket/src/tls.rs index 18dfb8bc..a46cffa1 100644 --- a/transports/websocket/src/tls.rs +++ b/transports/websocket/src/tls.rs @@ -29,7 +29,7 @@ pub struct Config { } impl fmt::Debug for Config { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Config") } } @@ -143,7 +143,7 @@ pub enum Error { } impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::Io(e) => write!(f, "i/o error: {}", e), Error::Tls(e) => write!(f, "tls error: {}", e), From 967f39656a73898004e6fb62087cbf5f2c170963 Mon Sep 17 00:00:00 2001 From: Cheng XU <3105373+xu-cheng@users.noreply.github.com> Date: Tue, 28 Jul 2020 04:26:27 -0700 Subject: [PATCH 4/6] core-derive: use full qualified name when polling NetworkBehaviour (#1681) * core-derive: use full qualified name when polling NetworkBehaviour If the users define a custom poll method also named in `poll` like `#[behaviour(poll_method = "poll")`, it will cause issues as the wrong `poll` method being called. So use full qualified name to avoid ambiguity. Fixes #1679. * Update changelog for patch release. Co-authored-by: Max Inden Co-authored-by: Roman S. Borschel --- misc/core-derive/CHANGELOG.md | 5 +++++ misc/core-derive/Cargo.toml | 2 +- misc/core-derive/src/lib.rs | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/misc/core-derive/CHANGELOG.md b/misc/core-derive/CHANGELOG.md index 15f337b5..4de00efd 100644 --- a/misc/core-derive/CHANGELOG.md +++ b/misc/core-derive/CHANGELOG.md @@ -1,3 +1,8 @@ +# 0.20.2 [2020-07-28] + +- Generate fully-qualified method name for `poll` to avoid +ambiguity. [PR 1681](https://github.com/libp2p/rust-libp2p/pull/1681). + # 0.20.1 [2020-07-08] - Allow users to opt out of the `NetworkBehaviourEventProcess` diff --git a/misc/core-derive/Cargo.toml b/misc/core-derive/Cargo.toml index a3ed9aad..03b64062 100644 --- a/misc/core-derive/Cargo.toml +++ b/misc/core-derive/Cargo.toml @@ -2,7 +2,7 @@ name = "libp2p-core-derive" edition = "2018" description = "Procedural macros of libp2p-core" -version = "0.20.1" +version = "0.20.2" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" diff --git a/misc/core-derive/src/lib.rs b/misc/core-derive/src/lib.rs index 8f873dd0..762a8bc7 100644 --- a/misc/core-derive/src/lib.rs +++ b/misc/core-derive/src/lib.rs @@ -435,7 +435,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { Some(quote!{ loop { - match #field_name.poll(cx, poll_params) { + match #trait_to_impl::poll(&mut #field_name, cx, poll_params) { #generate_event_match_arm std::task::Poll::Ready(#network_behaviour_action::DialAddress { address }) => { return std::task::Poll::Ready(#network_behaviour_action::DialAddress { address }); From 9662929f38fb8de874d8c4b49f59b9fd61ee9b63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCdiger=20Klaehn?= Date: Wed, 29 Jul 2020 09:25:53 +0200 Subject: [PATCH 5/6] Debug instance for the gossipsub behaviour (#1673) * Add debug instances for MessageCache and GossipSub behaviour * Manual impl of Debug for GossipsubMessage * Add pretty printing of protocol_id in debug * Use hex_fmt instead of hex * Inline StringOrBytes helper struct Since it is used only once here * Limit data of gossipsub msg to 20 bytes Otherwise they might become very large and useless for debugging --- protocols/gossipsub/Cargo.toml | 1 + protocols/gossipsub/src/behaviour.rs | 1 + protocols/gossipsub/src/config.rs | 6 +++++- protocols/gossipsub/src/mcache.rs | 12 +++++++++++- protocols/gossipsub/src/protocol.rs | 15 +++++++++++++-- 5 files changed, 31 insertions(+), 4 deletions(-) diff --git a/protocols/gossipsub/Cargo.toml b/protocols/gossipsub/Cargo.toml index 165d1737..59ccb548 100644 --- a/protocols/gossipsub/Cargo.toml +++ b/protocols/gossipsub/Cargo.toml @@ -26,6 +26,7 @@ base64 = "0.11.0" lru = "0.4.3" smallvec = "1.1.0" prost = "0.6.1" +hex_fmt = "0.3.0" [dev-dependencies] async-std = "1.6.2" diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index a959cad9..4f1ae52a 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -51,6 +51,7 @@ use wasm_timer::{Instant, Interval}; mod tests; +#[derive(Debug)] /// Network behaviour that handles the gossipsub protocol. pub struct Gossipsub { /// Configuration providing gossipsub performance parameters. diff --git a/protocols/gossipsub/src/config.rs b/protocols/gossipsub/src/config.rs index a01895ef..b00070a9 100644 --- a/protocols/gossipsub/src/config.rs +++ b/protocols/gossipsub/src/config.rs @@ -232,7 +232,11 @@ impl GossipsubConfigBuilder { impl std::fmt::Debug for GossipsubConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut builder = f.debug_struct("GossipsubConfig"); - let _ = builder.field("protocol_id", &self.protocol_id); + let _ = if let Ok(text) = std::str::from_utf8(&self.protocol_id) { + builder.field("protocol_id", &text) + } else { + builder.field("protocol_id", &hex_fmt::HexFmt(&self.protocol_id)) + }; let _ = builder.field("history_length", &self.history_length); let _ = builder.field("history_gossip", &self.history_gossip); let _ = builder.field("mesh_n", &self.mesh_n); diff --git a/protocols/gossipsub/src/mcache.rs b/protocols/gossipsub/src/mcache.rs index 6c284ae7..52c0be08 100644 --- a/protocols/gossipsub/src/mcache.rs +++ b/protocols/gossipsub/src/mcache.rs @@ -22,7 +22,7 @@ use crate::protocol::{GossipsubMessage, MessageId}; use crate::topic::TopicHash; -use std::collections::HashMap; +use std::{collections::HashMap, fmt}; /// CacheEntry stored in the history. #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -40,6 +40,16 @@ pub struct MessageCache { msg_id: fn(&GossipsubMessage) -> MessageId, } +impl fmt::Debug for MessageCache { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MessageCache") + .field("msgs", &self.msgs) + .field("history", &self.history) + .field("gossip", &self.gossip) + .finish() + } +} + /// Implementation of the MessageCache. impl MessageCache { pub fn new( diff --git a/protocols/gossipsub/src/protocol.rs b/protocols/gossipsub/src/protocol.rs index 14a8c6dd..53a75063 100644 --- a/protocols/gossipsub/src/protocol.rs +++ b/protocols/gossipsub/src/protocol.rs @@ -29,7 +29,7 @@ use futures::prelude::*; use futures_codec::{Decoder, Encoder, Framed}; use libp2p_core::{InboundUpgrade, OutboundUpgrade, PeerId, UpgradeInfo}; use prost::Message as ProtobufMessage; -use std::{borrow::Cow, io, iter, pin::Pin}; +use std::{borrow::Cow, fmt, io, iter, pin::Pin}; use unsigned_varint::codec; /// Implementation of the `ConnectionUpgrade` for the Gossipsub protocol. @@ -336,7 +336,7 @@ impl Into for MessageId { } /// A message received by the gossipsub system. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[derive(Clone, PartialEq, Eq, Hash)] pub struct GossipsubMessage { /// Id of the peer that published this message. pub source: PeerId, @@ -353,6 +353,17 @@ pub struct GossipsubMessage { pub topics: Vec, } +impl fmt::Debug for GossipsubMessage { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("GossipsubMessage") + .field("data",&format_args!("{:<20}", &hex_fmt::HexFmt(&self.data))) + .field("source", &self.source) + .field("sequence_number", &self.sequence_number) + .field("topics", &self.topics) + .finish() + } +} + /// A subscription received by the gossipsub system. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct GossipsubSubscription { From 3ebe916ef3ff111dbe866f43b8bc7bb35053c60f Mon Sep 17 00:00:00 2001 From: "Roman S. Borschel" Date: Wed, 29 Jul 2020 09:28:04 +0200 Subject: [PATCH 6/6] Update gossipsub changelog. --- protocols/gossipsub/CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/protocols/gossipsub/CHANGELOG.md b/protocols/gossipsub/CHANGELOG.md index d2a5c025..b1a156f3 100644 --- a/protocols/gossipsub/CHANGELOG.md +++ b/protocols/gossipsub/CHANGELOG.md @@ -1,3 +1,7 @@ +# 0.??.? [????-??-??] + +- `Debug` instance for `Gossipsub`. [PR 1673](https://github.com/libp2p/rust-libp2p/pull/1673). + # 0.20.0 [2020-07-01] - Updated dependencies.