From d79c93abdb8a6afd625813202014ac9b96bcc2ff Mon Sep 17 00:00:00 2001 From: Hannes <55623006+umgefahren@users.noreply.github.com> Date: Wed, 14 Dec 2022 16:45:04 +0100 Subject: [PATCH] chore: Implement latest clippy warnings (#3220) As I do frequently, I corrected for the latest clippy warnings. This will make sure the CI won't complain in the future. We could automate this btw and maybe run the nightly version of clippy. --- core/src/identity/ecdsa.rs | 2 +- core/src/identity/ed25519.rs | 2 +- core/src/identity/rsa.rs | 2 +- core/src/identity/secp256k1.rs | 2 +- core/src/signed_envelope.rs | 3 +- core/src/transport.rs | 2 +- core/src/transport/memory.rs | 6 +- core/src/transport/timeout.rs | 4 +- core/src/transport/upgrade.rs | 4 +- core/src/upgrade/transfer.rs | 5 +- examples/ipfs-private.rs | 5 +- misc/keygen/src/main.rs | 4 +- misc/multistream-select/src/negotiated.rs | 2 +- misc/multistream-select/src/protocol.rs | 8 +-- .../multistream-select/tests/dialer_select.rs | 2 +- muxers/mplex/benches/split_send_size.rs | 4 +- muxers/mplex/src/codec.rs | 4 +- muxers/mplex/src/io.rs | 12 ++-- protocols/autonat/examples/autonat_client.rs | 8 +-- protocols/autonat/examples/autonat_server.rs | 8 +-- protocols/autonat/tests/test_client.rs | 36 +++++------ protocols/autonat/tests/test_server.rs | 30 ++++----- protocols/dcutr/examples/dcutr.rs | 4 +- protocols/dcutr/tests/lib.rs | 10 +-- protocols/gossipsub/src/behaviour/tests.rs | 4 +- protocols/gossipsub/src/error.rs | 6 +- protocols/gossipsub/src/peer_score/params.rs | 5 +- protocols/gossipsub/src/peer_score/tests.rs | 63 +++++-------------- protocols/gossipsub/src/protocol.rs | 4 +- .../gossipsub/src/subscription_filter.rs | 4 +- protocols/gossipsub/tests/smoke.rs | 6 +- protocols/identify/examples/identify.rs | 10 +-- protocols/kad/src/behaviour/test.rs | 48 +++++++------- protocols/kad/src/handler.rs | 4 +- protocols/kad/src/jobs.rs | 4 +- protocols/kad/src/kbucket.rs | 6 +- protocols/kad/src/kbucket/bucket.rs | 10 +-- protocols/kad/src/query/peers/closest.rs | 2 +- .../kad/src/query/peers/closest/disjoint.rs | 3 +- protocols/ping/src/handler.rs | 2 +- protocols/ping/tests/ping.rs | 4 +- protocols/relay/examples/relay_v2.rs | 8 +-- protocols/relay/tests/v2.rs | 8 +-- protocols/rendezvous/src/codec.rs | 2 +- protocols/rendezvous/src/handler/inbound.rs | 2 +- protocols/rendezvous/tests/harness.rs | 4 +- protocols/request-response/tests/ping.rs | 14 ++--- swarm-derive/src/lib.rs | 2 +- swarm/src/connection/error.rs | 14 ++--- swarm/src/handler.rs | 2 +- swarm/src/handler/multi.rs | 2 +- swarm/src/lib.rs | 38 +++++------ transports/dns/src/lib.rs | 12 ++-- transports/noise/tests/smoke.rs | 2 +- transports/plaintext/src/error.rs | 2 +- transports/pnet/src/lib.rs | 8 +-- transports/quic/src/connection.rs | 3 +- transports/quic/src/endpoint.rs | 2 +- transports/quic/src/transport.rs | 4 +- transports/quic/tests/smoke.rs | 2 +- transports/tcp/src/lib.rs | 14 ++--- transports/tls/src/certificate.rs | 2 +- transports/tls/src/verifier.rs | 4 +- transports/tls/tests/smoke.rs | 4 +- transports/wasm-ext/src/lib.rs | 4 +- transports/webrtc/src/tokio/fingerprint.rs | 2 +- transports/webrtc/src/tokio/transport.rs | 4 +- transports/webrtc/src/tokio/udp_mux.rs | 8 +-- transports/webrtc/tests/smoke.rs | 2 +- transports/websocket/src/error.rs | 10 +-- transports/websocket/src/framed.rs | 6 +- transports/websocket/src/tls.rs | 6 +- 72 files changed, 244 insertions(+), 307 deletions(-) diff --git a/core/src/identity/ecdsa.rs b/core/src/identity/ecdsa.rs index 9c2ef903..c8063fde 100644 --- a/core/src/identity/ecdsa.rs +++ b/core/src/identity/ecdsa.rs @@ -218,7 +218,7 @@ impl fmt::Debug for PublicKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("PublicKey(asn.1 uncompressed): ")?; for byte in &self.encode_der() { - write!(f, "{:x}", byte)?; + write!(f, "{byte:x}")?; } Ok(()) } diff --git a/core/src/identity/ed25519.rs b/core/src/identity/ed25519.rs index 48cddf10..64c54a2f 100644 --- a/core/src/identity/ed25519.rs +++ b/core/src/identity/ed25519.rs @@ -122,7 +122,7 @@ impl fmt::Debug for PublicKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("PublicKey(compressed): ")?; for byte in self.0.as_bytes() { - write!(f, "{:x}", byte)?; + write!(f, "{byte:x}")?; } Ok(()) } diff --git a/core/src/identity/rsa.rs b/core/src/identity/rsa.rs index e3c10a6e..12f5d75e 100644 --- a/core/src/identity/rsa.rs +++ b/core/src/identity/rsa.rs @@ -120,7 +120,7 @@ impl fmt::Debug for PublicKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("PublicKey(PKCS1): ")?; for byte in &self.0 { - write!(f, "{:x}", byte)?; + write!(f, "{byte:x}")?; } Ok(()) } diff --git a/core/src/identity/secp256k1.rs b/core/src/identity/secp256k1.rs index 51aa073f..119c3ef6 100644 --- a/core/src/identity/secp256k1.rs +++ b/core/src/identity/secp256k1.rs @@ -158,7 +158,7 @@ impl fmt::Debug for PublicKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("PublicKey(compressed): ")?; for byte in &self.encode() { - write!(f, "{:x}", byte)?; + write!(f, "{byte:x}")?; } Ok(()) } diff --git a/core/src/signed_envelope.rs b/core/src/signed_envelope.rs index 10acdf3c..d290354f 100644 --- a/core/src/signed_envelope.rs +++ b/core/src/signed_envelope.rs @@ -168,8 +168,7 @@ impl fmt::Display for ReadPayloadError { Self::InvalidSignature => write!(f, "Invalid signature"), Self::UnexpectedPayloadType { expected, got } => write!( f, - "Unexpected payload type, expected {:?} but got {:?}", - expected, got + "Unexpected payload type, expected {expected:?} but got {got:?}" ), } } diff --git a/core/src/transport.rs b/core/src/transport.rs index 0c989177..04196efc 100644 --- a/core/src/transport.rs +++ b/core/src/transport.rs @@ -541,7 +541,7 @@ where fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { TransportError::MultiaddrNotSupported(addr) => { - write!(f, "Multiaddr is not supported: {}", addr) + write!(f, "Multiaddr is not supported: {addr}") } TransportError::Other(_) => Ok(()), } diff --git a/core/src/transport/memory.rs b/core/src/transport/memory.rs index c08fe945..65105b42 100644 --- a/core/src/transport/memory.rs +++ b/core/src/transport/memory.rs @@ -500,7 +500,7 @@ mod tests { #[test] fn stop_listening() { let rand_port = rand::random::().saturating_add(1); - let addr: Multiaddr = format!("/memory/{}", rand_port).parse().unwrap(); + let addr: Multiaddr = format!("/memory/{rand_port}").parse().unwrap(); let mut transport = MemoryTransport::default().boxed(); futures::executor::block_on(async { @@ -520,7 +520,7 @@ mod tests { assert_eq!(id, listener_id); assert!(reason.is_ok()) } - other => panic!("Unexpected transport event: {:?}", other), + other => panic!("Unexpected transport event: {other:?}"), } assert!(!transport.remove_listener(listener_id)); }) @@ -533,7 +533,7 @@ mod tests { // Setup listener. let rand_port = rand::random::().saturating_add(1); - let t1_addr: Multiaddr = format!("/memory/{}", rand_port).parse().unwrap(); + let t1_addr: Multiaddr = format!("/memory/{rand_port}").parse().unwrap(); let cloned_t1_addr = t1_addr.clone(); let mut t1 = MemoryTransport::default().boxed(); diff --git a/core/src/transport/timeout.rs b/core/src/transport/timeout.rs index 5c3867b3..c796e6f0 100644 --- a/core/src/transport/timeout.rs +++ b/core/src/transport/timeout.rs @@ -198,8 +198,8 @@ where fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { TransportTimeoutError::Timeout => write!(f, "Timeout has been reached"), - TransportTimeoutError::TimerError(err) => write!(f, "Error in the timer: {}", err), - TransportTimeoutError::Other(err) => write!(f, "{}", err), + TransportTimeoutError::TimerError(err) => write!(f, "Error in the timer: {err}"), + TransportTimeoutError::Other(err) => write!(f, "{err}"), } } } diff --git a/core/src/transport/upgrade.rs b/core/src/transport/upgrade.rs index 8fc04547..4f282960 100644 --- a/core/src/transport/upgrade.rs +++ b/core/src/transport/upgrade.rs @@ -471,8 +471,8 @@ where { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - TransportUpgradeError::Transport(e) => write!(f, "Transport error: {}", e), - TransportUpgradeError::Upgrade(e) => write!(f, "Upgrade error: {}", e), + TransportUpgradeError::Transport(e) => write!(f, "Transport error: {e}"), + TransportUpgradeError::Upgrade(e) => write!(f, "Upgrade error: {e}"), } } } diff --git a/core/src/upgrade/transfer.rs b/core/src/upgrade/transfer.rs index baea400a..93aeb987 100644 --- a/core/src/upgrade/transfer.rs +++ b/core/src/upgrade/transfer.rs @@ -113,10 +113,7 @@ pub async fn read_length_prefixed( if len > max_size { return Err(io::Error::new( io::ErrorKind::InvalidData, - format!( - "Received data size ({} bytes) exceeds maximum ({} bytes)", - len, max_size - ), + format!("Received data size ({len} bytes) exceeds maximum ({max_size} bytes)"), )); } diff --git a/examples/ipfs-private.rs b/examples/ipfs-private.rs index 1d89f5f9..db3907f4 100644 --- a/examples/ipfs-private.rs +++ b/examples/ipfs-private.rs @@ -103,10 +103,7 @@ fn strip_peer_id(addr: &mut Multiaddr) { Some(Protocol::P2p(peer_id)) => { let mut addr = Multiaddr::empty(); addr.push(Protocol::P2p(peer_id)); - println!( - "removing peer id {} so this address can be dialed by rust-libp2p", - addr - ); + println!("removing peer id {addr} so this address can be dialed by rust-libp2p"); } Some(other) => addr.push(other), _ => {} diff --git a/misc/keygen/src/main.rs b/misc/keygen/src/main.rs index 4d298477..328f872e 100644 --- a/misc/keygen/src/main.rs +++ b/misc/keygen/src/main.rs @@ -71,13 +71,13 @@ fn main() -> Result<(), Box> { Command::Rand { prefix } => { if let Some(prefix) = prefix { if prefix.as_bytes().iter().any(|c| !ALPHABET.contains(c)) { - eprintln!("Prefix {} is not valid base58", prefix); + eprintln!("Prefix {prefix} is not valid base58"); std::process::exit(1); } // Checking conformity to ALLOWED_FIRST_BYTE. if !prefix.is_empty() && !ALLOWED_FIRST_BYTE.contains(&prefix.as_bytes()[0]) { - eprintln!("Prefix {} is not reachable", prefix); + eprintln!("Prefix {prefix} is not reachable"); eprintln!( "Only the following bytes are possible as first byte: {}", str::from_utf8(ALLOWED_FIRST_BYTE).unwrap() diff --git a/misc/multistream-select/src/negotiated.rs b/misc/multistream-select/src/negotiated.rs index 2f78daf0..dabcec4f 100644 --- a/misc/multistream-select/src/negotiated.rs +++ b/misc/multistream-select/src/negotiated.rs @@ -378,7 +378,7 @@ impl fmt::Display for NegotiationError { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { match self { NegotiationError::ProtocolError(p) => { - fmt.write_fmt(format_args!("Protocol error: {}", p)) + fmt.write_fmt(format_args!("Protocol error: {p}")) } NegotiationError::Failed => fmt.write_str("Protocol negotiation failed."), } diff --git a/misc/multistream-select/src/protocol.rs b/misc/multistream-select/src/protocol.rs index 5809e176..65cdb40f 100644 --- a/misc/multistream-select/src/protocol.rs +++ b/misc/multistream-select/src/protocol.rs @@ -443,7 +443,7 @@ impl Error for ProtocolError { impl fmt::Display for ProtocolError { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { match self { - ProtocolError::IoError(e) => write!(fmt, "I/O error: {}", e), + ProtocolError::IoError(e) => write!(fmt, "I/O error: {e}"), ProtocolError::InvalidMessage => write!(fmt, "Received an invalid message."), ProtocolError::InvalidProtocol => write!(fmt, "A protocol (name) is invalid."), ProtocolError::TooManyProtocols => write!(fmt, "Too many protocols received."), @@ -465,7 +465,7 @@ mod tests { .filter(|&c| c.is_ascii_alphanumeric()) .take(n) .collect(); - Protocol(Bytes::from(format!("/{}", p))) + Protocol(Bytes::from(format!("/{p}"))) } } @@ -487,10 +487,10 @@ mod tests { fn prop(msg: Message) { let mut buf = BytesMut::new(); msg.encode(&mut buf) - .unwrap_or_else(|_| panic!("Encoding message failed: {:?}", msg)); + .unwrap_or_else(|_| panic!("Encoding message failed: {msg:?}")); match Message::decode(buf.freeze()) { Ok(m) => assert_eq!(m, msg), - Err(e) => panic!("Decoding failed: {:?}", e), + Err(e) => panic!("Decoding failed: {e:?}"), } } quickcheck(prop as fn(_)) diff --git a/misc/multistream-select/tests/dialer_select.rs b/misc/multistream-select/tests/dialer_select.rs index 66fd1593..378c8c15 100644 --- a/misc/multistream-select/tests/dialer_select.rs +++ b/misc/multistream-select/tests/dialer_select.rs @@ -92,7 +92,7 @@ fn negotiation_failed() { Ok((_, io)) => io, Err(NegotiationError::Failed) => return, Err(NegotiationError::ProtocolError(e)) => { - panic!("Unexpected protocol error {}", e) + panic!("Unexpected protocol error {e}") } }; match io.complete().await { diff --git a/muxers/mplex/benches/split_send_size.rs b/muxers/mplex/benches/split_send_size.rs index 80eb09c5..65cc76ee 100644 --- a/muxers/mplex/benches/split_send_size.rs +++ b/muxers/mplex/benches/split_send_size.rs @@ -60,7 +60,7 @@ fn prepare(c: &mut Criterion) { tcp.throughput(Throughput::Bytes(payload.len() as u64)); let mut receiver_transport = tcp_transport(size); let mut sender_transport = tcp_transport(size); - tcp.bench_function(format!("{}", size), |b| { + tcp.bench_function(format!("{size}"), |b| { b.iter(|| { run( black_box(&mut receiver_transport), @@ -79,7 +79,7 @@ fn prepare(c: &mut Criterion) { mem.throughput(Throughput::Bytes(payload.len() as u64)); let mut receiver_transport = mem_transport(size); let mut sender_transport = mem_transport(size); - mem.bench_function(format!("{}", size), |b| { + mem.bench_function(format!("{size}"), |b| { b.iter(|| { run( black_box(&mut receiver_transport), diff --git a/muxers/mplex/src/codec.rs b/muxers/mplex/src/codec.rs index f7d986a8..76dbddb3 100644 --- a/muxers/mplex/src/codec.rs +++ b/muxers/mplex/src/codec.rs @@ -205,7 +205,7 @@ impl Decoder for Codec { CodecDecodeState::HasHeader(header) => match self.varint_decoder.decode(src)? { Some(len) => { if len as usize > MAX_FRAME_SIZE { - let msg = format!("Mplex frame length {} exceeds maximum", len); + let msg = format!("Mplex frame length {len} exceeds maximum"); return Err(io::Error::new(io::ErrorKind::InvalidData, msg)); } @@ -252,7 +252,7 @@ impl Decoder for Codec { stream_id: RemoteStreamId::dialer(num), }, _ => { - let msg = format!("Invalid mplex header value 0x{:x}", header); + let msg = format!("Invalid mplex header value 0x{header:x}"); return Err(io::Error::new(io::ErrorKind::InvalidData, msg)); } }; diff --git a/muxers/mplex/src/io.rs b/muxers/mplex/src/io.rs index 9d0d9939..f1d6fa9b 100644 --- a/muxers/mplex/src/io.rs +++ b/muxers/mplex/src/io.rs @@ -1220,7 +1220,7 @@ mod tests { for i in 0..cfg.max_substreams { match m.poll_next_stream(cx) { Poll::Pending => panic!("Expected new inbound stream."), - Poll::Ready(Err(e)) => panic!("{:?}", e), + Poll::Ready(Err(e)) => panic!("{e:?}"), Poll::Ready(Ok(id)) => { assert_eq!(id, LocalStreamId::listener(i as u64)); } @@ -1231,7 +1231,7 @@ mod tests { // after reading and buffering data frames up to the limit. let id = LocalStreamId::listener(0); match m.poll_next_stream(cx) { - Poll::Ready(r) => panic!("Unexpected result for next stream: {:?}", r), + Poll::Ready(r) => panic!("Unexpected result for next stream: {r:?}"), Poll::Pending => { // We expect the implementation to yield when the buffer // is full but before it is exceeded and the max buffer @@ -1243,7 +1243,7 @@ mod tests { cfg.max_buffer_len ); match m.poll_next_stream(cx) { - Poll::Ready(r) => panic!("Unexpected result for next stream: {:?}", r), + Poll::Ready(r) => panic!("Unexpected result for next stream: {r:?}"), Poll::Pending => { // Expect the buffer for stream 0 to be exceeded, triggering // the max. buffer behaviour. @@ -1281,7 +1281,7 @@ mod tests { Poll::Ready(Ok(Some(bytes))) => { assert_eq!(bytes, data); } - x => panic!("Unexpected: {:?}", x), + x => panic!("Unexpected: {x:?}"), } } @@ -1293,7 +1293,7 @@ mod tests { // Expect to read EOF match m.poll_read_stream(cx, id) { Poll::Ready(Ok(None)) => {} - poll => panic!("Unexpected: {:?}", poll), + poll => panic!("Unexpected: {poll:?}"), } } MaxBufferBehaviour::Block => { @@ -1301,7 +1301,7 @@ mod tests { match m.poll_read_stream(cx, id) { Poll::Ready(Ok(Some(bytes))) => assert_eq!(bytes, data), Poll::Pending => assert_eq!(overflow.get(), 1), - poll => panic!("Unexpected: {:?}", poll), + poll => panic!("Unexpected: {poll:?}"), } } } diff --git a/protocols/autonat/examples/autonat_client.rs b/protocols/autonat/examples/autonat_client.rs index c124dcf9..2932b835 100644 --- a/protocols/autonat/examples/autonat_client.rs +++ b/protocols/autonat/examples/autonat_client.rs @@ -64,7 +64,7 @@ async fn main() -> Result<(), Box> { let local_key = identity::Keypair::generate_ed25519(); let local_peer_id = PeerId::from(local_key.public()); - println!("Local peer id: {:?}", local_peer_id); + println!("Local peer id: {local_peer_id:?}"); let transport = tcp::async_io::Transport::default() .upgrade(Version::V1) @@ -88,9 +88,9 @@ async fn main() -> Result<(), Box> { loop { match swarm.select_next_some().await { - SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {:?}", address), - SwarmEvent::Behaviour(event) => println!("{:?}", event), - e => println!("{:?}", e), + SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {address:?}"), + SwarmEvent::Behaviour(event) => println!("{event:?}"), + e => println!("{e:?}"), } } } diff --git a/protocols/autonat/examples/autonat_server.rs b/protocols/autonat/examples/autonat_server.rs index a5e98012..68735bf2 100644 --- a/protocols/autonat/examples/autonat_server.rs +++ b/protocols/autonat/examples/autonat_server.rs @@ -53,7 +53,7 @@ async fn main() -> Result<(), Box> { let local_key = identity::Keypair::generate_ed25519(); let local_peer_id = PeerId::from(local_key.public()); - println!("Local peer id: {:?}", local_peer_id); + println!("Local peer id: {local_peer_id:?}"); let transport = tcp::async_io::Transport::default() .upgrade(Version::V1) @@ -72,9 +72,9 @@ async fn main() -> Result<(), Box> { loop { match swarm.select_next_some().await { - SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {:?}", address), - SwarmEvent::Behaviour(event) => println!("{:?}", event), - e => println!("{:?}", e), + SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {address:?}"), + SwarmEvent::Behaviour(event) => println!("{event:?}"), + e => println!("{e:?}"), } } } diff --git a/protocols/autonat/tests/test_client.rs b/protocols/autonat/tests/test_client.rs index 1fd03925..8006d3db 100644 --- a/protocols/autonat/tests/test_client.rs +++ b/protocols/autonat/tests/test_client.rs @@ -122,7 +122,7 @@ async fn test_auto_probe() { assert!(peer.is_none()); assert_eq!(error, OutboundProbeError::NoAddresses); } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } assert_eq!(client.behaviour().nat_status(), NatStatus::Unknown); @@ -140,7 +140,7 @@ async fn test_auto_probe() { assert_eq!(peer, server_id); probe_id } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), }; match next_event(&mut client).await { @@ -156,7 +156,7 @@ async fn test_auto_probe() { OutboundProbeError::Response(ResponseError::DialError) ); } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } match next_event(&mut client).await { @@ -164,7 +164,7 @@ async fn test_auto_probe() { assert_eq!(old, NatStatus::Unknown); assert_eq!(new, NatStatus::Private); } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } assert_eq!(client.behaviour().confidence(), 0); @@ -186,7 +186,7 @@ async fn test_auto_probe() { assert_eq!(peer, server_id); probe_id } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), }; let mut had_connection_event = false; @@ -216,7 +216,7 @@ async fn test_auto_probe() { SwarmEvent::IncomingConnection { .. } | SwarmEvent::NewListenAddr { .. } | SwarmEvent::ExpiredListenAddr { .. } => {} - other => panic!("Unexpected swarm event: {:?}.", other), + other => panic!("Unexpected swarm event: {other:?}."), } } @@ -230,7 +230,7 @@ async fn test_auto_probe() { } if endpoint.is_listener() => { assert_eq!(peer_id, server_id); } - other => panic!("Unexpected swarm event: {:?}.", other), + other => panic!("Unexpected swarm event: {other:?}."), } } @@ -282,7 +282,7 @@ async fn test_confidence() { assert_eq!(peer, server_id); probe_id } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), }; match next_event(&mut client).await { @@ -302,12 +302,12 @@ async fn test_confidence() { ); (peer.unwrap(), probe_id) } - other => panic!("Unexpected Outbound Event: {:?}", other), + other => panic!("Unexpected Outbound Event: {other:?}"), }; assert_eq!(peer, server_id); assert_eq!(probe_id, id); } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } // Confidence should increase each iteration up to MAX_CONFIDENCE @@ -326,7 +326,7 @@ async fn test_confidence() { assert_eq!(old, NatStatus::Unknown); assert_eq!(new.is_public(), test_public); } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } } } @@ -373,7 +373,7 @@ async fn test_throttle_server_period() { } Event::OutboundProbe(OutboundProbeEvent::Request { .. }) => {} Event::OutboundProbe(OutboundProbeEvent::Response { .. }) => {} - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } } @@ -386,7 +386,7 @@ async fn test_throttle_server_period() { assert!(peer.is_none()); assert_eq!(error, OutboundProbeError::NoServer); } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } assert_eq!(client.behaviour().confidence(), 0); }; @@ -431,14 +431,14 @@ async fn test_use_connected_as_server() { Event::OutboundProbe(OutboundProbeEvent::Request { peer, .. }) => { assert_eq!(peer, server_id); } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } match next_event(&mut client).await { Event::OutboundProbe(OutboundProbeEvent::Response { peer, .. }) => { assert_eq!(peer, server_id); } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } }; @@ -487,7 +487,7 @@ async fn test_outbound_failure() { } Event::OutboundProbe(OutboundProbeEvent::Request { .. }) => {} Event::OutboundProbe(OutboundProbeEvent::Response { .. }) => {} - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } } @@ -511,7 +511,7 @@ async fn test_outbound_failure() { }) => { assert!(inactive_ids.contains(&peer)); } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } } }; @@ -563,7 +563,7 @@ async fn test_global_ips_config() { Event::OutboundProbe(OutboundProbeEvent::Error { error, .. }) => { assert!(matches!(error, OutboundProbeError::NoServer)) } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } }; diff --git a/protocols/autonat/tests/test_server.rs b/protocols/autonat/tests/test_server.rs index 140bb928..44ad7fdf 100644 --- a/protocols/autonat/tests/test_server.rs +++ b/protocols/autonat/tests/test_server.rs @@ -167,7 +167,7 @@ async fn test_dial_back() { SwarmEvent::IncomingConnection { .. } | SwarmEvent::NewListenAddr { .. } | SwarmEvent::ExpiredListenAddr { .. } => {} - other => panic!("Unexpected swarm event: {:?}.", other), + other => panic!("Unexpected swarm event: {other:?}."), } }; let expect_addr = Multiaddr::empty() @@ -185,7 +185,7 @@ async fn test_dial_back() { assert_eq!(addresses[0], expect_addr); probe_id } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), }; loop { @@ -209,7 +209,7 @@ async fn test_dial_back() { } SwarmEvent::Dialing(peer) => assert_eq!(peer, client_id), SwarmEvent::NewListenAddr { .. } | SwarmEvent::ExpiredListenAddr { .. } => {} - other => panic!("Unexpected swarm event: {:?}.", other), + other => panic!("Unexpected swarm event: {other:?}."), } } @@ -223,7 +223,7 @@ async fn test_dial_back() { assert_eq!(peer, client_id); assert_eq!(address, expect_addr); } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } }; @@ -241,7 +241,7 @@ async fn test_dial_error() { assert_eq!(peer, client_id); probe_id } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), }; loop { @@ -253,7 +253,7 @@ async fn test_dial_error() { } SwarmEvent::Dialing(peer) => assert_eq!(peer, client_id), SwarmEvent::NewListenAddr { .. } | SwarmEvent::ExpiredListenAddr { .. } => {} - other => panic!("Unexpected swarm event: {:?}.", other), + other => panic!("Unexpected swarm event: {other:?}."), } } @@ -267,7 +267,7 @@ async fn test_dial_error() { assert_eq!(peer, client_id); assert_eq!(error, InboundProbeError::Response(ResponseError::DialError)); } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } }; @@ -295,7 +295,7 @@ async fn test_throttle_global_max() { Event::InboundProbe(InboundProbeEvent::Request { peer, probe_id, .. }) => { (probe_id, peer) } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), }; loop { @@ -313,7 +313,7 @@ async fn test_throttle_global_max() { assert_eq!(first_peer_id, peer); assert_eq!(first_probe_id, probe_id); } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), }; } }; @@ -340,7 +340,7 @@ async fn test_throttle_peer_max() { assert_eq!(client_id, peer); probe_id } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), }; match next_event(&mut server).await { @@ -348,7 +348,7 @@ async fn test_throttle_peer_max() { assert_eq!(peer, client_id); assert_eq!(probe_id, first_probe_id); } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), } match next_event(&mut server).await { @@ -364,7 +364,7 @@ async fn test_throttle_peer_max() { InboundProbeError::Response(ResponseError::DialRefused) ) } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), }; }; @@ -393,7 +393,7 @@ async fn test_dial_multiple_addr() { assert_eq!(client_id, peer); addresses } - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), }; loop { @@ -417,7 +417,7 @@ async fn test_dial_multiple_addr() { } SwarmEvent::Dialing(peer) => assert_eq!(peer, client_id), SwarmEvent::NewListenAddr { .. } | SwarmEvent::ExpiredListenAddr { .. } => {} - other => panic!("Unexpected swarm event: {:?}.", other), + other => panic!("Unexpected swarm event: {other:?}."), } } }; @@ -444,7 +444,7 @@ async fn test_global_ips_config() { error, InboundProbeError::Response(ResponseError::DialRefused) )), - other => panic!("Unexpected behaviour event: {:?}.", other), + other => panic!("Unexpected behaviour event: {other:?}."), }; }; diff --git a/protocols/dcutr/examples/dcutr.rs b/protocols/dcutr/examples/dcutr.rs index 1ff7d1f3..73cc7350 100644 --- a/protocols/dcutr/examples/dcutr.rs +++ b/protocols/dcutr/examples/dcutr.rs @@ -185,7 +185,7 @@ fn main() -> Result<(), Box> { SwarmEvent::NewListenAddr { address, .. } => { info!("Listening on {:?}", address); } - event => panic!("{:?}", event), + event => panic!("{event:?}"), } } _ = delay => { @@ -220,7 +220,7 @@ fn main() -> Result<(), Box> { info!("Relay told us our public address: {:?}", observed_addr); learned_observed_addr = true; } - event => panic!("{:?}", event), + event => panic!("{event:?}"), } if learned_observed_addr && told_relay_observed_addr { diff --git a/protocols/dcutr/tests/lib.rs b/protocols/dcutr/tests/lib.rs index 6400fa93..b204d407 100644 --- a/protocols/dcutr/tests/lib.rs +++ b/protocols/dcutr/tests/lib.rs @@ -83,7 +83,7 @@ fn connect() { remote_peer_id, remote_relayed_addr, } if remote_peer_id == dst_peer_id && remote_relayed_addr == dst_relayed_addr => {} - e => panic!("Unexpected event: {:?}.", e), + e => panic!("Unexpected event: {e:?}."), } pool.run_until(wait_for_connection_established( &mut src, @@ -210,7 +210,7 @@ async fn wait_for_reservation( } SwarmEvent::Dialing(peer_id) if peer_id == relay_peer_id => {} SwarmEvent::ConnectionEstablished { peer_id, .. } if peer_id == relay_peer_id => {} - e => panic!("{:?}", e), + e => panic!("{e:?}"), } } } @@ -229,7 +229,7 @@ async fn wait_for_connection_established(client: &mut Swarm, addr: &Mult client::Event::OutboundCircuitEstablished { .. }, )) => {} SwarmEvent::ConnectionEstablished { .. } => {} - e => panic!("{:?}", e), + e => panic!("{e:?}"), } } } @@ -237,7 +237,7 @@ async fn wait_for_connection_established(client: &mut Swarm, addr: &Mult async fn wait_for_new_listen_addr(client: &mut Swarm, new_addr: &Multiaddr) { match client.select_next_some().await { SwarmEvent::NewListenAddr { address, .. } if address == *new_addr => {} - e => panic!("{:?}", e), + e => panic!("{e:?}"), } } @@ -245,7 +245,7 @@ async fn wait_for_dcutr_event(client: &mut Swarm) -> dcutr::behaviour::E loop { match client.select_next_some().await { SwarmEvent::Behaviour(ClientEvent::Dcutr(e)) => return e, - e => panic!("{:?}", e), + e => panic!("{e:?}"), } } } diff --git a/protocols/gossipsub/src/behaviour/tests.rs b/protocols/gossipsub/src/behaviour/tests.rs index 9bf32d8f..42c28061 100644 --- a/protocols/gossipsub/src/behaviour/tests.rs +++ b/protocols/gossipsub/src/behaviour/tests.rs @@ -4767,8 +4767,8 @@ fn test_iwant_penalties() { assert!(i > 9); double_penalized += 1 } else { - println!("{}", peer); - println!("{}", score); + println!("{peer}"); + println!("{score}"); panic!("Invalid score of peer"); } } diff --git a/protocols/gossipsub/src/error.rs b/protocols/gossipsub/src/error.rs index 6654db8d..1ebca61e 100644 --- a/protocols/gossipsub/src/error.rs +++ b/protocols/gossipsub/src/error.rs @@ -42,7 +42,7 @@ pub enum PublishError { impl std::fmt::Display for PublishError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } @@ -67,7 +67,7 @@ pub enum SubscriptionError { impl std::fmt::Display for SubscriptionError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } @@ -128,7 +128,7 @@ pub enum ValidationError { impl std::fmt::Display for ValidationError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } diff --git a/protocols/gossipsub/src/peer_score/params.rs b/protocols/gossipsub/src/peer_score/params.rs index c4159bb6..35bea0e4 100644 --- a/protocols/gossipsub/src/peer_score/params.rs +++ b/protocols/gossipsub/src/peer_score/params.rs @@ -174,10 +174,7 @@ impl PeerScoreParams { pub fn validate(&self) -> Result<(), String> { for (topic, params) in self.topics.iter() { if let Err(e) = params.validate() { - return Err(format!( - "Invalid score parameters for topic {}: {}", - topic, e - )); + return Err(format!("Invalid score parameters for topic {topic}: {e}")); } } diff --git a/protocols/gossipsub/src/peer_score/tests.rs b/protocols/gossipsub/src/peer_score/tests.rs index 3616452a..52ce8c1d 100644 --- a/protocols/gossipsub/src/peer_score/tests.rs +++ b/protocols/gossipsub/src/peer_score/tests.rs @@ -100,8 +100,7 @@ fn test_score_time_in_mesh() { let score = peer_score.score(&peer_id); assert!( score == 0.0, - "expected score to start at zero. Score found: {}", - score + "expected score to start at zero. Score found: {score}" ); // The time in mesh depends on how long the peer has been grafted @@ -116,9 +115,7 @@ fn test_score_time_in_mesh() { * (elapsed.as_millis() / topic_params.time_in_mesh_quantum.as_millis()) as f64; assert!( score >= expected, - "The score: {} should be greater than or equal to: {}", - score, - expected + "The score: {score} should be greater than or equal to: {expected}" ); } @@ -148,8 +145,7 @@ fn test_score_time_in_mesh_cap() { let score = peer_score.score(&peer_id); assert!( score == 0.0, - "expected score to start at zero. Score found: {}", - score + "expected score to start at zero. Score found: {score}" ); // The time in mesh depends on how long the peer has been grafted @@ -210,12 +206,7 @@ fn test_score_first_message_deliveries() { let score = peer_score.score(&peer_id); let expected = topic_params.topic_weight * topic_params.first_message_deliveries_weight * messages as f64; - assert!( - score == expected, - "The score: {} should be {}", - score, - expected - ); + assert!(score == expected, "The score: {score} should be {expected}"); } #[test] @@ -256,12 +247,7 @@ fn test_score_first_message_deliveries_cap() { let expected = topic_params.topic_weight * topic_params.first_message_deliveries_weight * topic_params.first_message_deliveries_cap; - assert!( - score == expected, - "The score: {} should be {}", - score, - expected - ); + assert!(score == expected, "The score: {score} should be {expected}"); } #[test] @@ -300,12 +286,7 @@ fn test_score_first_message_deliveries_decay() { * topic_params.first_message_deliveries_weight * topic_params.first_message_deliveries_decay * messages as f64; - assert!( - score == expected, - "The score: {} should be {}", - score, - expected - ); + assert!(score == expected, "The score: {score} should be {expected}"); // refreshing the scores applies the decay param let decay_intervals = 10; @@ -314,12 +295,7 @@ fn test_score_first_message_deliveries_decay() { expected *= topic_params.first_message_deliveries_decay; } let score = peer_score.score(&peer_id); - assert!( - score == expected, - "The score: {} should be {}", - score, - expected - ); + assert!(score == expected, "The score: {score} should be {expected}"); } #[test] @@ -368,8 +344,7 @@ fn test_score_mesh_message_deliveries() { let score = peer_score.score(peer_id); assert!( score >= 0.0, - "expected no mesh delivery penalty before activation time, got score {}", - score + "expected no mesh delivery penalty before activation time, got score {score}" ); } @@ -402,13 +377,11 @@ fn test_score_mesh_message_deliveries() { assert!( score_a >= 0.0, - "expected non-negative score for Peer A, got score {}", - score_a + "expected non-negative score for Peer A, got score {score_a}" ); assert!( score_b >= 0.0, - "expected non-negative score for Peer B, got score {}", - score_b + "expected non-negative score for Peer B, got score {score_b}" ); // the penalty is the difference between the threshold and the actual mesh deliveries, squared. @@ -418,12 +391,7 @@ fn test_score_mesh_message_deliveries() { let expected = topic_params.topic_weight * topic_params.mesh_message_deliveries_weight * penalty; - assert!( - score_c == expected, - "Score: {}. Expected {}", - score_c, - expected - ); + assert!(score_c == expected, "Score: {score_c}. Expected {expected}"); } #[test] @@ -469,8 +437,7 @@ fn test_score_mesh_message_deliveries_decay() { let score_a = peer_score.score(&peer_id_a); assert!( score_a >= 0.0, - "expected non-negative score for Peer A, got score {}", - score_a + "expected non-negative score for Peer A, got score {score_a}" ); let mut decayed_delivery_count = (messages as f64) * topic_params.mesh_message_deliveries_decay; @@ -545,13 +512,11 @@ fn test_score_mesh_failure_penalty() { let score_b = peer_score.score(&peer_id_b); assert!( score_a >= 0.0, - "expected non-negative score for Peer A, got score {}", - score_a + "expected non-negative score for Peer A, got score {score_a}" ); assert!( score_b >= 0.0, - "expected non-negative score for Peer B, got score {}", - score_b + "expected non-negative score for Peer B, got score {score_b}" ); // prune peer B to apply the penalty diff --git a/protocols/gossipsub/src/protocol.rs b/protocols/gossipsub/src/protocol.rs index ff0bd1c0..07610d91 100644 --- a/protocols/gossipsub/src/protocol.rs +++ b/protocols/gossipsub/src/protocol.rs @@ -107,11 +107,11 @@ impl ProtocolId { let protocol_id = match kind { PeerKind::Gossipsubv1_1 => match prefix { true => format!("/{}/{}", id, "1.1.0"), - false => format!("{}", id), + false => format!("{id}"), }, PeerKind::Gossipsub => match prefix { true => format!("/{}/{}", id, "1.0.0"), - false => format!("{}", id), + false => format!("{id}"), }, PeerKind::Floodsub => format!("/{}/{}", "floodsub", "1.0.0"), // NOTE: This is used for informing the behaviour of unsupported peers. We do not diff --git a/protocols/gossipsub/src/subscription_filter.rs b/protocols/gossipsub/src/subscription_filter.rs index ca4204cc..ec6cb675 100644 --- a/protocols/gossipsub/src/subscription_filter.rs +++ b/protocols/gossipsub/src/subscription_filter.rs @@ -354,7 +354,7 @@ mod test { #[test] fn test_filter_incoming_too_many_subscriptions() { let t: Vec<_> = (0..4) - .map(|i| TopicHash::from_raw(format!("t{}", i))) + .map(|i| TopicHash::from_raw(format!("t{i}"))) .collect(); let mut filter = MaxCountSubscriptionFilter { @@ -383,7 +383,7 @@ mod test { #[test] fn test_filter_incoming_max_subscribed_valid() { let t: Vec<_> = (0..5) - .map(|i| TopicHash::from_raw(format!("t{}", i))) + .map(|i| TopicHash::from_raw(format!("t{i}"))) .collect(); let mut filter = MaxCountSubscriptionFilter { diff --git a/protocols/gossipsub/tests/smoke.rs b/protocols/gossipsub/tests/smoke.rs index b89a37a2..40605d2a 100644 --- a/protocols/gossipsub/tests/smoke.rs +++ b/protocols/gossipsub/tests/smoke.rs @@ -216,8 +216,7 @@ fn multi_hop_propagation() { }); if !all_subscribed { return TestResult::error(format!( - "Timed out waiting for all nodes to subscribe but only have {:?}/{:?}.", - subscribed, num_nodes, + "Timed out waiting for all nodes to subscribe but only have {subscribed:?}/{num_nodes:?}.", )); } @@ -246,8 +245,7 @@ fn multi_hop_propagation() { }); if !all_received { return TestResult::error(format!( - "Timed out waiting for all nodes to receive the msg but only have {:?}/{:?}.", - received_msgs, num_nodes, + "Timed out waiting for all nodes to receive the msg but only have {received_msgs:?}/{num_nodes:?}.", )); } diff --git a/protocols/identify/examples/identify.rs b/protocols/identify/examples/identify.rs index b7962b40..12fe084a 100644 --- a/protocols/identify/examples/identify.rs +++ b/protocols/identify/examples/identify.rs @@ -47,7 +47,7 @@ use std::error::Error; async fn main() -> Result<(), Box> { let local_key = identity::Keypair::generate_ed25519(); let local_peer_id = PeerId::from(local_key.public()); - println!("Local peer id: {:?}", local_peer_id); + println!("Local peer id: {local_peer_id:?}"); let transport = libp2p_tcp::async_io::Transport::default() .upgrade(Version::V1) @@ -72,19 +72,19 @@ async fn main() -> Result<(), Box> { if let Some(addr) = std::env::args().nth(1) { let remote: Multiaddr = addr.parse()?; swarm.dial(remote)?; - println!("Dialed {}", addr) + println!("Dialed {addr}") } loop { match swarm.select_next_some().await { - SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {:?}", address), + SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {address:?}"), // Prints peer id identify info is being sent to. SwarmEvent::Behaviour(identify::Event::Sent { peer_id, .. }) => { - println!("Sent identify info to {:?}", peer_id) + println!("Sent identify info to {peer_id:?}") } // Prints out the info received via the identify event SwarmEvent::Behaviour(identify::Event::Received { info, .. }) => { - println!("Received {:?}", info) + println!("Received {info:?}") } _ => {} } diff --git a/protocols/kad/src/behaviour/test.rs b/protocols/kad/src/behaviour/test.rs index 4808dd65..bf3bd7cf 100644 --- a/protocols/kad/src/behaviour/test.rs +++ b/protocols/kad/src/behaviour/test.rs @@ -219,7 +219,7 @@ fn bootstrap() { } // Ignore any other event. Poll::Ready(Some(_)) => (), - e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), + e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"), Poll::Pending => break, } } @@ -261,9 +261,9 @@ fn query_iter() { assert_eq!(&key[..], search_target.to_bytes().as_slice()); assert_eq!(usize::from(step.count), 1); } - i => panic!("Unexpected query info: {:?}", i), + i => panic!("Unexpected query info: {i:?}"), }, - None => panic!("Query not found: {:?}", qid), + None => panic!("Query not found: {qid:?}"), } // Set up expectations. @@ -295,7 +295,7 @@ fn query_iter() { } // Ignore any other event. Poll::Ready(Some(_)) => (), - e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), + e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"), Poll::Pending => break, } } @@ -348,7 +348,7 @@ fn unresponsive_not_returned_direct() { } // Ignore any other event. Poll::Ready(Some(_)) => (), - e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), + e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"), Poll::Pending => break, } } @@ -409,7 +409,7 @@ fn unresponsive_not_returned_indirect() { } // Ignore any other event. Poll::Ready(Some(_)) => (), - e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), + e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"), Poll::Pending => break, } } @@ -466,12 +466,12 @@ fn get_record_not_found() { assert!(closest_peers.contains(&swarm_ids[2])); return Poll::Ready(()); } else { - panic!("Unexpected error result: {:?}", e); + panic!("Unexpected error result: {e:?}"); } } // Ignore any other event. Poll::Ready(Some(_)) => (), - e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), + e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"), Poll::Pending => break, } } @@ -555,9 +555,9 @@ fn put_record() { assert!(record.expires.is_some()); qids.insert(qid); } - i => panic!("Unexpected query info: {:?}", i), + i => panic!("Unexpected query info: {i:?}"), }, - None => panic!("Query not found: {:?}", qid), + None => panic!("Query not found: {qid:?}"), } } @@ -595,7 +595,7 @@ fn put_record() { assert_eq!(usize::from(index.count), 1); assert!(index.last); match res { - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), Ok(ok) => { assert!(records.contains_key(&ok.key)); let record = swarm.behaviour_mut().store.get(&ok.key).unwrap(); @@ -630,7 +630,7 @@ fn put_record() { } // Ignore any other event. Poll::Ready(Some(_)) => (), - e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), + e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"), Poll::Pending => break, } } @@ -693,16 +693,14 @@ fn put_record() { actual.difference(&expected).collect::>(); assert!( actual_not_expected.is_empty(), - "Did not expect records to be stored on nodes {:?}.", - actual_not_expected, + "Did not expect records to be stored on nodes {actual_not_expected:?}.", ); let expected_not_actual = expected.difference(&actual).collect::>(); assert!( expected_not_actual.is_empty(), - "Expected record to be stored on nodes {:?}.", - expected_not_actual, + "Expected record to be stored on nodes {expected_not_actual:?}.", ); } } @@ -791,7 +789,7 @@ fn get_record() { } // Ignore any other event. Poll::Ready(Some(_)) => (), - e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), + e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"), Poll::Pending => break, } } @@ -849,7 +847,7 @@ fn get_record_many() { } // Ignore any other event. Poll::Ready(Some(_)) => (), - e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), + e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"), Poll::Pending => break, } } @@ -939,7 +937,7 @@ fn add_provider() { ))) => { assert!(qids.is_empty() || qids.remove(&id)); match res { - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), Ok(ok) => { assert!(keys.contains(&ok.key)); results.push(ok.key); @@ -948,7 +946,7 @@ fn add_provider() { } // Ignore any other event. Poll::Ready(Some(_)) => (), - e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), + e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"), Poll::Pending => break, } } @@ -1066,7 +1064,7 @@ fn exceed_jobs_max_queries() { result: QueryResult::GetClosestPeers(Ok(r)), .. }) => break assert!(r.peers.is_empty()), - SwarmEvent::Behaviour(e) => panic!("Unexpected event: {:?}", e), + SwarmEvent::Behaviour(e) => panic!("Unexpected event: {e:?}"), _ => {} } } else { @@ -1158,7 +1156,7 @@ fn disjoint_query_does_not_finish_before_all_paths_did() { assert_eq!(r.peer, Some(addr_trudy)); } Ok(_) => {} - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } // Ignore any other event. @@ -1184,7 +1182,7 @@ fn disjoint_query_does_not_finish_before_all_paths_did() { QueryInfo::GetRecord { step, .. } => { assert_eq!(usize::from(step.count), 2); } - i => panic!("Unexpected query info: {:?}", i), + i => panic!("Unexpected query info: {i:?}"), }); // Poll `alice` and `bob` expecting `alice` to return a successful query @@ -1368,7 +1366,7 @@ fn get_providers_single() { result: QueryResult::StartProviding(Ok(_)), .. }) => {} - SwarmEvent::Behaviour(e) => panic!("Unexpected event: {:?}", e), + SwarmEvent::Behaviour(e) => panic!("Unexpected event: {e:?}"), _ => {} } }); @@ -1398,7 +1396,7 @@ fn get_providers_single() { } } } - SwarmEvent::Behaviour(e) => panic!("Unexpected event: {:?}", e), + SwarmEvent::Behaviour(e) => panic!("Unexpected event: {e:?}"), _ => {} } } diff --git a/protocols/kad/src/handler.rs b/protocols/kad/src/handler.rs index 345762d4..d012c94d 100644 --- a/protocols/kad/src/handler.rs +++ b/protocols/kad/src/handler.rs @@ -362,7 +362,7 @@ impl fmt::Display for KademliaHandlerQueryErr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { KademliaHandlerQueryErr::Upgrade(err) => { - write!(f, "Error while performing Kademlia query: {}", err) + write!(f, "Error while performing Kademlia query: {err}") } KademliaHandlerQueryErr::UnexpectedMessage => { write!( @@ -371,7 +371,7 @@ impl fmt::Display for KademliaHandlerQueryErr { ) } KademliaHandlerQueryErr::Io(err) => { - write!(f, "I/O error during a Kademlia RPC query: {}", err) + write!(f, "I/O error during a Kademlia RPC query: {err}") } } } diff --git a/protocols/kad/src/jobs.rs b/protocols/kad/src/jobs.rs index 8855026e..2cb4002a 100644 --- a/protocols/kad/src/jobs.rs +++ b/protocols/kad/src/jobs.rs @@ -100,7 +100,7 @@ impl PeriodicJob { /// for the delay to expire. fn asap(&mut self) { if let PeriodicJobState::Waiting(delay, deadline) = &mut self.state { - let new_deadline = Instant::now() - Duration::from_secs(1); + let new_deadline = Instant::now().checked_sub(Duration::from_secs(1)).unwrap(); *deadline = new_deadline; delay.reset(Duration::from_secs(1)); } @@ -181,7 +181,7 @@ impl PutRecordJob { /// The job is guaranteed to run on the next invocation of `poll`. pub fn asap(&mut self, publish: bool) { if publish { - self.next_publish = Some(Instant::now() - Duration::from_secs(1)) + self.next_publish = Some(Instant::now().checked_sub(Duration::from_secs(1)).unwrap()) } self.inner.asap() } diff --git a/protocols/kad/src/kbucket.rs b/protocols/kad/src/kbucket.rs index 82b88b29..cef1e702 100644 --- a/protocols/kad/src/kbucket.rs +++ b/protocols/kad/src/kbucket.rs @@ -724,17 +724,17 @@ mod tests { // Expire the timeout for the pending entry on the full bucket.` let full_bucket = &mut table.buckets[full_bucket_index.unwrap().get()]; - let elapsed = Instant::now() - Duration::from_secs(1); + let elapsed = Instant::now().checked_sub(Duration::from_secs(1)).unwrap(); full_bucket.pending_mut().unwrap().set_ready_at(elapsed); match table.entry(&expected_applied.inserted.key) { Entry::Present(_, NodeStatus::Connected) => {} - x => panic!("Unexpected entry: {:?}", x), + x => panic!("Unexpected entry: {x:?}"), } match table.entry(&expected_applied.evicted.as_ref().unwrap().key) { Entry::Absent(_) => {} - x => panic!("Unexpected entry: {:?}", x), + x => panic!("Unexpected entry: {x:?}"), } assert_eq!(Some(expected_applied), table.take_applied_pending()); diff --git a/protocols/kad/src/kbucket/bucket.rs b/protocols/kad/src/kbucket/bucket.rs index 0a6b6900..c03b011d 100644 --- a/protocols/kad/src/kbucket/bucket.rs +++ b/protocols/kad/src/kbucket/bucket.rs @@ -548,7 +548,7 @@ mod tests { let node = Node { key, value: () }; match bucket.insert(node, NodeStatus::Disconnected) { InsertResult::Full => {} - x => panic!("{:?}", x), + x => panic!("{x:?}"), } // One-by-one fill the bucket with connected nodes, replacing the disconnected ones. @@ -568,20 +568,20 @@ mod tests { InsertResult::Pending { disconnected } => { assert_eq!(disconnected, first_disconnected.key) } - x => panic!("{:?}", x), + x => panic!("{x:?}"), } // Trying to insert another connected node fails. match bucket.insert(node.clone(), NodeStatus::Connected) { InsertResult::Full => {} - x => panic!("{:?}", x), + x => panic!("{x:?}"), } assert!(bucket.pending().is_some()); // Apply the pending node. let pending = bucket.pending_mut().expect("No pending node."); - pending.set_ready_at(Instant::now() - Duration::from_secs(1)); + pending.set_ready_at(Instant::now().checked_sub(Duration::from_secs(1)).unwrap()); let result = bucket.apply_pending(); assert_eq!( result, @@ -603,7 +603,7 @@ mod tests { let node = Node { key, value: () }; match bucket.insert(node, NodeStatus::Connected) { InsertResult::Full => {} - x => panic!("{:?}", x), + x => panic!("{x:?}"), } } diff --git a/protocols/kad/src/query/peers/closest.rs b/protocols/kad/src/query/peers/closest.rs index 7fe87b7f..d56f6ce5 100644 --- a/protocols/kad/src/query/peers/closest.rs +++ b/protocols/kad/src/query/peers/closest.rs @@ -750,7 +750,7 @@ mod tests { } => { assert_eq!(key.preimage(), &peer); } - Peer { state, .. } => panic!("Unexpected peer state: {:?}", state), + Peer { state, .. } => panic!("Unexpected peer state: {state:?}"), } let finished = iter.is_finished(); diff --git a/protocols/kad/src/query/peers/closest/disjoint.rs b/protocols/kad/src/query/peers/closest/disjoint.rs index 6a818713..d8713bb3 100644 --- a/protocols/kad/src/query/peers/closest/disjoint.rs +++ b/protocols/kad/src/query/peers/closest/disjoint.rs @@ -933,8 +933,7 @@ mod tests { panic!( "Expected `ClosestDisjointPeersIter` to find all peers \ - found by `ClosestPeersIter`, but it did not find {:?}.", - closest_only, + found by `ClosestPeersIter`, but it did not find {closest_only:?}.", ); }; diff --git a/protocols/ping/src/handler.rs b/protocols/ping/src/handler.rs index 67d4b66c..2703b274 100644 --- a/protocols/ping/src/handler.rs +++ b/protocols/ping/src/handler.rs @@ -159,7 +159,7 @@ impl fmt::Display for Failure { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Failure::Timeout => f.write_str("Ping timeout"), - Failure::Other { error } => write!(f, "Ping error: {}", error), + Failure::Other { error } => write!(f, "Ping error: {error}"), Failure::Unsupported => write!(f, "Ping protocol not supported"), } } diff --git a/protocols/ping/tests/ping.rs b/protocols/ping/tests/ping.rs index 9939dc49..c4eaea4e 100644 --- a/protocols/ping/tests/ping.rs +++ b/protocols/ping/tests/ping.rs @@ -75,7 +75,7 @@ fn ping_pong() { result: Err(e), .. })) => { - panic!("Ping failure: {:?}", e) + panic!("Ping failure: {e:?}") } _ => {} } @@ -101,7 +101,7 @@ fn ping_pong() { result: Err(e), .. })) => { - panic!("Ping failure: {:?}", e) + panic!("Ping failure: {e:?}") } _ => {} } diff --git a/protocols/relay/examples/relay_v2.rs b/protocols/relay/examples/relay_v2.rs index 575b8a70..ac633dd1 100644 --- a/protocols/relay/examples/relay_v2.rs +++ b/protocols/relay/examples/relay_v2.rs @@ -38,12 +38,12 @@ fn main() -> Result<(), Box> { env_logger::init(); let opt = Opt::parse(); - println!("opt: {:?}", opt); + println!("opt: {opt:?}"); // Create a static known PeerId based on given secret let local_key: identity::Keypair = generate_ed25519(opt.secret_key_seed); let local_peer_id = PeerId::from(local_key.public()); - println!("Local peer id: {:?}", local_peer_id); + println!("Local peer id: {local_peer_id:?}"); let tcp_transport = tcp::async_io::Transport::default(); @@ -80,10 +80,10 @@ fn main() -> Result<(), Box> { loop { match swarm.next().await.expect("Infinite Stream.") { SwarmEvent::Behaviour(Event::Relay(event)) => { - println!("{:?}", event) + println!("{event:?}") } SwarmEvent::NewListenAddr { address, .. } => { - println!("Listening on {:?}", address); + println!("Listening on {address:?}"); } _ => {} } diff --git a/protocols/relay/tests/v2.rs b/protocols/relay/tests/v2.rs index 07383a3c..a91253fb 100644 --- a/protocols/relay/tests/v2.rs +++ b/protocols/relay/tests/v2.rs @@ -166,7 +166,7 @@ fn new_reservation_to_same_relay_replaces_old() { } } SwarmEvent::Behaviour(ClientEvent::Ping(_)) => {} - e => panic!("{:?}", e), + e => panic!("{e:?}"), } } }); @@ -226,7 +226,7 @@ fn connect() { SwarmEvent::ConnectionEstablished { peer_id, .. } if peer_id == dst_peer_id => { break } - e => panic!("{:?}", e), + e => panic!("{e:?}"), } } }) @@ -434,7 +434,7 @@ async fn wait_for_reservation( } } SwarmEvent::Behaviour(ClientEvent::Ping(_)) => {} - e => panic!("{:?}", e), + e => panic!("{e:?}"), } } } @@ -448,7 +448,7 @@ async fn wait_for_dial(client: &mut Swarm, remote: PeerId) -> bool { return false } SwarmEvent::Behaviour(ClientEvent::Ping(_)) => {} - e => panic!("{:?}", e), + e => panic!("{e:?}"), } } } diff --git a/protocols/rendezvous/src/codec.rs b/protocols/rendezvous/src/codec.rs index 88af5a1f..b1479541 100644 --- a/protocols/rendezvous/src/codec.rs +++ b/protocols/rendezvous/src/codec.rs @@ -50,7 +50,7 @@ impl Namespace { /// This will panic if the namespace is too long. We accepting panicking in this case because we are enforcing a `static lifetime which means this value can only be a constant in the program and hence we hope the developer checked that it is of an acceptable length. pub fn from_static(value: &'static str) -> Self { if value.len() > 255 { - panic!("Namespace '{}' is too long!", value) + panic!("Namespace '{value}' is too long!") } Namespace(value.to_owned()) diff --git a/protocols/rendezvous/src/handler/inbound.rs b/protocols/rendezvous/src/handler/inbound.rs index 3f432bee..aba68bd1 100644 --- a/protocols/rendezvous/src/handler/inbound.rs +++ b/protocols/rendezvous/src/handler/inbound.rs @@ -116,7 +116,7 @@ impl SubstreamHandler for Stream { Stream::PendingSend(substream, Message::DiscoverResponse(Err(error))) } (event, inbound) => { - debug_assert!(false, "{:?} cannot handle event {:?}", inbound, event); + debug_assert!(false, "{inbound:?} cannot handle event {event:?}"); inbound } diff --git a/protocols/rendezvous/tests/harness.rs b/protocols/rendezvous/tests/harness.rs index d22f0eb2..460df22b 100644 --- a/protocols/rendezvous/tests/harness.rs +++ b/protocols/rendezvous/tests/harness.rs @@ -59,7 +59,7 @@ where fn get_rand_memory_address() -> Multiaddr { let address_port = rand::random::(); - format!("/memory/{}", address_port) + format!("/memory/{address_port}") .parse::() .unwrap() } @@ -176,7 +176,7 @@ where listener_done = true; } SwarmEvent::IncomingConnectionError { error, .. } => { - panic!("Failure in incoming connection {}", error); + panic!("Failure in incoming connection {error}"); } other => { log::debug!("Ignoring {:?}", other); diff --git a/protocols/request-response/tests/ping.rs b/protocols/request-response/tests/ping.rs index 72c77c3a..9837f6d6 100644 --- a/protocols/request-response/tests/ping.rs +++ b/protocols/request-response/tests/ping.rs @@ -62,7 +62,7 @@ fn is_response_outbound() { assert_eq!(&offline_peer, &peer); assert_eq!(req_id, request_id1); } - e => panic!("Peer: Unexpected event: {:?}", e), + e => panic!("Peer: Unexpected event: {e:?}"), } let request_id2 = swarm1.behaviour_mut().send_request(&offline_peer, ping); @@ -121,7 +121,7 @@ fn ping_protocol() { SwarmEvent::Behaviour(Event::ResponseSent { peer, .. }) => { assert_eq!(&peer, &peer2_id); } - SwarmEvent::Behaviour(e) => panic!("Peer1: Unexpected event: {:?}", e), + SwarmEvent::Behaviour(e) => panic!("Peer1: Unexpected event: {e:?}"), _ => {} } } @@ -156,7 +156,7 @@ fn ping_protocol() { req_id = swarm2.behaviour_mut().send_request(&peer1_id, ping.clone()); } } - SwarmEvent::Behaviour(e) => panic!("Peer2: Unexpected event: {:?}", e), + SwarmEvent::Behaviour(e) => panic!("Peer2: Unexpected event: {e:?}"), _ => {} } } @@ -203,12 +203,12 @@ fn emits_inbound_connection_closed_failure() { assert_eq!(&peer, &peer2_id); break channel; }, - SwarmEvent::Behaviour(ev) => panic!("Peer1: Unexpected event: {:?}", ev), + SwarmEvent::Behaviour(ev) => panic!("Peer1: Unexpected event: {ev:?}"), _ => {} }, event = swarm2.select_next_some() => { if let SwarmEvent::Behaviour(ev) = event { - panic!("Peer2: Unexpected event: {:?}", ev); + panic!("Peer2: Unexpected event: {ev:?}"); } } ) @@ -223,7 +223,7 @@ fn emits_inbound_connection_closed_failure() { error: InboundFailure::ConnectionClosed, .. }) => break, - SwarmEvent::Behaviour(e) => panic!("Peer1: Unexpected event: {:?}", e), + SwarmEvent::Behaviour(e) => panic!("Peer1: Unexpected event: {e:?}"), _ => {} } } @@ -285,7 +285,7 @@ fn emits_inbound_connection_closed_if_channel_is_dropped() { let error = match event { Event::OutboundFailure { error, .. } => error, - e => panic!("unexpected event from peer 2: {:?}", e), + e => panic!("unexpected event from peer 2: {e:?}"), }; assert_eq!(error, OutboundFailure::ConnectionClosed); diff --git a/swarm-derive/src/lib.rs b/swarm-derive/src/lib.rs index 4af70e6a..b142ea77 100644 --- a/swarm-derive/src/lib.rs +++ b/swarm-derive/src/lib.rs @@ -725,7 +725,7 @@ fn get_meta_items(attr: &syn::Attribute) -> Option> { Ok(syn::Meta::List(ref meta)) => Some(meta.nested.iter().cloned().collect()), Ok(_) => None, Err(e) => { - eprintln!("error parsing attribute metadata: {}", e); + eprintln!("error parsing attribute metadata: {e}"); None } } diff --git a/swarm/src/connection/error.rs b/swarm/src/connection/error.rs index db51ebca..541d458d 100644 --- a/swarm/src/connection/error.rs +++ b/swarm/src/connection/error.rs @@ -43,11 +43,11 @@ where { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ConnectionError::IO(err) => write!(f, "Connection error: I/O error: {}", err), + ConnectionError::IO(err) => write!(f, "Connection error: I/O error: {err}"), ConnectionError::KeepAliveTimeout => { write!(f, "Connection closed due to expired keep-alive timeout.") } - ConnectionError::Handler(err) => write!(f, "Connection error: Handler error: {}", err), + ConnectionError::Handler(err) => write!(f, "Connection error: Handler error: {err}"), } } } @@ -130,23 +130,21 @@ where { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - PendingConnectionError::IO(err) => write!(f, "Pending connection: I/O error: {}", err), + PendingConnectionError::IO(err) => write!(f, "Pending connection: I/O error: {err}"), PendingConnectionError::Aborted => write!(f, "Pending connection: Aborted."), PendingConnectionError::Transport(err) => { write!( f, - "Pending connection: Transport error on connection: {}", - err + "Pending connection: Transport error on connection: {err}" ) } PendingConnectionError::ConnectionLimit(l) => { - write!(f, "Connection error: Connection limit: {}.", l) + write!(f, "Connection error: Connection limit: {l}.") } PendingConnectionError::WrongPeerId { obtained, endpoint } => { write!( f, - "Pending connection: Unexpected peer ID {} at {:?}.", - obtained, endpoint + "Pending connection: Unexpected peer ID {obtained} at {endpoint:?}." ) } } diff --git a/swarm/src/handler.rs b/swarm/src/handler.rs index 8d34509c..2a4e1d44 100644 --- a/swarm/src/handler.rs +++ b/swarm/src/handler.rs @@ -564,7 +564,7 @@ where ConnectionHandlerUpgrErr::Timer => { write!(f, "Timer error while opening a substream") } - ConnectionHandlerUpgrErr::Upgrade(err) => write!(f, "{}", err), + ConnectionHandlerUpgrErr::Upgrade(err) => write!(f, "{err}"), } } } diff --git a/swarm/src/handler/multi.rs b/swarm/src/handler/multi.rs index c1f937c1..d80b51c5 100644 --- a/swarm/src/handler/multi.rs +++ b/swarm/src/handler/multi.rs @@ -560,7 +560,7 @@ impl DuplicateProtonameError { impl fmt::Display for DuplicateProtonameError { 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) + write!(f, "duplicate protocol name: {s}") } else { write!(f, "duplicate protocol name: {:?}", self.0) } diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index a2ef648d..cf6051e1 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -1658,33 +1658,27 @@ impl From> for DialError { impl fmt::Display for DialError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - DialError::ConnectionLimit(err) => write!(f, "Dial error: {}", err), + DialError::ConnectionLimit(err) => write!(f, "Dial error: {err}"), DialError::NoAddresses => write!(f, "Dial error: no addresses for peer."), DialError::LocalPeerId => write!(f, "Dial error: tried to dial local peer id."), DialError::Banned => write!(f, "Dial error: peer is banned."), DialError::DialPeerConditionFalse(c) => { - write!( - f, - "Dial error: condition {:?} for dialing peer was false.", - c - ) + write!(f, "Dial error: condition {c:?} for dialing peer was false.") } DialError::Aborted => write!( f, "Dial error: Pending connection attempt has been aborted." ), DialError::InvalidPeerId(multihash) => { - write!(f, "Dial error: multihash {:?} is not a PeerId", multihash) + write!(f, "Dial error: multihash {multihash:?} is not a PeerId") } DialError::WrongPeerId { obtained, endpoint } => write!( f, - "Dial error: Unexpected peer ID {} at {:?}.", - obtained, endpoint + "Dial error: Unexpected peer ID {obtained} at {endpoint:?}." ), DialError::ConnectionIo(e) => write!( f, - "Dial error: An I/O error occurred on the connection: {:?}.", - e + "Dial error: An I/O error occurred on the connection: {e:?}." ), DialError::Transport(errors) => { write!(f, "Failed to negotiate transport protocol(s): [")?; @@ -2263,7 +2257,7 @@ mod tests { panic!("Unexpected transport event.") } Either::Right((e, _)) => { - panic!("Expect swarm to not emit any event {:?}", e) + panic!("Expect swarm to not emit any event {e:?}") } } } @@ -2271,7 +2265,7 @@ mod tests { match swarm.next().await.unwrap() { SwarmEvent::OutgoingConnectionError { .. } => {} - e => panic!("Unexpected swarm event {:?}", e), + e => panic!("Unexpected swarm event {e:?}"), } }) } @@ -2311,7 +2305,7 @@ mod tests { assert_eq!(limit.current, outgoing_limit); assert_eq!(limit.limit, outgoing_limit); } - e => panic!("Unexpected error: {:?}", e), + e => panic!("Unexpected error: {e:?}"), } let info = network.network_info(); @@ -2351,7 +2345,7 @@ mod tests { let listen_addr = async_std::task::block_on(poll_fn(|cx| { match ready!(network1.poll_next_unpin(cx)).unwrap() { SwarmEvent::NewListenAddr { address, .. } => Poll::Ready(address), - e => panic!("Unexpected network event: {:?}", e), + e => panic!("Unexpected network event: {e:?}"), } })); @@ -2390,7 +2384,7 @@ mod tests { Poll::Pending => { network_1_pending = true; } - e => panic!("Unexpected network event: {:?}", e), + e => panic!("Unexpected network event: {e:?}"), } match network2.poll_next_unpin(cx) { @@ -2408,7 +2402,7 @@ mod tests { Poll::Pending => { network_2_pending = true; } - e => panic!("Unexpected network event: {:?}", e), + e => panic!("Unexpected network event: {e:?}"), } if network_1_pending && network_2_pending { @@ -2478,7 +2472,7 @@ mod tests { Poll::Ready(Some(SwarmEvent::OutgoingConnectionError { peer_id, error, .. })) => Poll::Ready((peer_id, error)), - Poll::Ready(x) => panic!("unexpected {:?}", x), + Poll::Ready(x) => panic!("unexpected {x:?}"), Poll::Pending => Poll::Pending, } })); @@ -2494,7 +2488,7 @@ mod tests { } ); } - x => panic!("wrong error {:?}", x), + x => panic!("wrong error {x:?}"), } } @@ -2555,7 +2549,7 @@ mod tests { assert_eq!(local_addr, local_address); } Poll::Ready(ev) => { - panic!("Unexpected event: {:?}", ev) + panic!("Unexpected event: {ev:?}") } Poll::Pending => break Poll::Pending, } @@ -2631,7 +2625,7 @@ mod tests { listener.listen_on(multiaddr![Memory(0u64)]).unwrap(); let listener_address = match block_on(listener.next()).unwrap() { SwarmEvent::NewListenAddr { address, .. } => address, - e => panic!("Unexpected network event: {:?}", e), + e => panic!("Unexpected network event: {e:?}"), }; dialer @@ -2651,7 +2645,7 @@ mod tests { error: DialError::Aborted, .. } => {} - e => panic!("Unexpected swarm event {:?}.", e), + e => panic!("Unexpected swarm event {e:?}."), } } diff --git a/transports/dns/src/lib.rs b/transports/dns/src/lib.rs index 3d67b628..8ea3967c 100644 --- a/transports/dns/src/lib.rs +++ b/transports/dns/src/lib.rs @@ -410,9 +410,9 @@ where { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - DnsErr::Transport(err) => write!(f, "{}", err), - DnsErr::ResolveError(err) => write!(f, "{}", err), - DnsErr::MultiaddrNotSupported(a) => write!(f, "Unsupported resolved address: {}", a), + DnsErr::Transport(err) => write!(f, "{err}"), + DnsErr::ResolveError(err) => write!(f, "{err}"), + DnsErr::MultiaddrNotSupported(a) => write!(f, "Unsupported resolved address: {a}"), DnsErr::TooManyLookups => write!(f, "Too many DNS lookups"), } } @@ -692,7 +692,7 @@ mod tests { .await { Err(DnsErr::ResolveError(_)) => {} - Err(e) => panic!("Unexpected error: {:?}", e), + Err(e) => panic!("Unexpected error: {e:?}"), Ok(_) => panic!("Unexpected success."), } @@ -704,9 +704,9 @@ mod tests { { Err(DnsErr::ResolveError(e)) => match e.kind() { ResolveErrorKind::NoRecordsFound { .. } => {} - _ => panic!("Unexpected DNS error: {:?}", e), + _ => panic!("Unexpected DNS error: {e:?}"), }, - Err(e) => panic!("Unexpected error: {:?}", e), + Err(e) => panic!("Unexpected error: {e:?}"), Ok(_) => panic!("Unexpected success."), } } diff --git a/transports/noise/tests/smoke.rs b/transports/noise/tests/smoke.rs index 7abfa205..56b5e139 100644 --- a/transports/noise/tests/smoke.rs +++ b/transports/noise/tests/smoke.rs @@ -294,7 +294,7 @@ fn run( match server_session.read_exact(&mut n).await { Ok(()) => u64::from_be_bytes(n), Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => 0, - Err(e) => panic!("error reading len: {}", e), + Err(e) => panic!("error reading len: {e}"), } }; info!("server: reading message ({} bytes)", len); diff --git a/transports/plaintext/src/error.rs b/transports/plaintext/src/error.rs index 63930602..3943bb06 100644 --- a/transports/plaintext/src/error.rs +++ b/transports/plaintext/src/error.rs @@ -70,7 +70,7 @@ impl error::Error for PlainTextError { impl fmt::Display for PlainTextError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { match self { - PlainTextError::IoError(e) => write!(f, "I/O error: {}", e), + PlainTextError::IoError(e) => write!(f, "I/O error: {e}"), PlainTextError::InvalidPayload(_) => f.write_str("Failed to decode protobuf"), PlainTextError::PeerIdMismatch => f.write_str( "The peer id of the exchange isn't consistent with the remote public key", diff --git a/transports/pnet/src/lib.rs b/transports/pnet/src/lib.rs index b92735c2..7b2aa073 100644 --- a/transports/pnet/src/lib.rs +++ b/transports/pnet/src/lib.rs @@ -102,7 +102,7 @@ fn to_hex(bytes: &[u8]) -> String { let mut hex = String::with_capacity(bytes.len() * 2); for byte in bytes { - write!(hex, "{:02x}", byte).expect("Can't fail on writing to string"); + write!(hex, "{byte:02x}").expect("Can't fail on writing to string"); } hex @@ -174,7 +174,7 @@ pub enum KeyParseError { impl fmt::Display for KeyParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } @@ -310,8 +310,8 @@ impl fmt::Display for PnetError { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { match self { - PnetError::HandshakeError(e) => write!(f, "Handshake error: {}", e), - PnetError::IoError(e) => write!(f, "I/O error: {}", e), + PnetError::HandshakeError(e) => write!(f, "Handshake error: {e}"), + PnetError::IoError(e) => write!(f, "I/O error: {e}"), } } } diff --git a/transports/quic/src/connection.rs b/transports/quic/src/connection.rs index 9a16a314..0e88d24e 100644 --- a/transports/quic/src/connection.rs +++ b/transports/quic/src/connection.rs @@ -236,8 +236,7 @@ impl StreamMuxer for Connection { quinn_proto::Event::Connected | quinn_proto::Event::HandshakeDataReady => { debug_assert!( false, - "Unexpected event {:?} on established QUIC connection", - event + "Unexpected event {event:?} on established QUIC connection" ); } quinn_proto::Event::ConnectionLost { reason } => { diff --git a/transports/quic/src/endpoint.rs b/transports/quic/src/endpoint.rs index 3eab4c59..024062e3 100644 --- a/transports/quic/src/endpoint.rs +++ b/transports/quic/src/endpoint.rs @@ -520,7 +520,7 @@ impl Driver

{ // `event` has type `quinn_proto::ConnectionEvent`, which has multiple // variants. `quinn_proto::Endpoint::handle` however only ever returns // `ConnectionEvent::Datagram`. - debug_assert!(format!("{:?}", event).contains("Datagram")); + debug_assert!(format!("{event:?}").contains("Datagram")); // Redirect the datagram to its connection. if let Some(sender) = self.alive_connections.get_mut(&connec_id) { diff --git a/transports/quic/src/transport.rs b/transports/quic/src/transport.rs index 01e52ec6..8d122424 100644 --- a/transports/quic/src/transport.rs +++ b/transports/quic/src/transport.rs @@ -771,7 +771,7 @@ mod test { ); assert!(matches!(listen_addr.iter().nth(2), Some(Protocol::QuicV1))); } - e => panic!("Unexpected event: {:?}", e), + e => panic!("Unexpected event: {e:?}"), } assert!(transport.remove_listener(id), "Expect listener to exist."); match poll_fn(|cx| Pin::new(&mut transport).as_mut().poll(cx)).await { @@ -781,7 +781,7 @@ mod test { } => { assert_eq!(listener_id, id); } - e => panic!("Unexpected event: {:?}", e), + e => panic!("Unexpected event: {e:?}"), } // Poll once again so that the listener has the chance to return `Poll::Ready(None)` and // be removed from the list of listeners. diff --git a/transports/quic/tests/smoke.rs b/transports/quic/tests/smoke.rs index bd6dd3f1..a1478645 100644 --- a/transports/quic/tests/smoke.rs +++ b/transports/quic/tests/smoke.rs @@ -405,7 +405,7 @@ async fn start_listening(transport: &mut Boxed<(PeerId, StreamMuxerBox)>, addr: transport.listen_on(addr.parse().unwrap()).unwrap(); match transport.next().await { Some(TransportEvent::NewAddress { listen_addr, .. }) => listen_addr, - e => panic!("{:?}", e), + e => panic!("{e:?}"), } } diff --git a/transports/tcp/src/lib.rs b/transports/tcp/src/lib.rs index c36152b2..3caa3935 100644 --- a/transports/tcp/src/lib.rs +++ b/transports/tcp/src/lib.rs @@ -952,7 +952,7 @@ mod tests { upgrade.write_all(&[4, 5, 6]).await.unwrap(); return; } - e => panic!("Unexpected transport event: {:?}", e), + e => panic!("Unexpected transport event: {e:?}"), } } } @@ -1016,12 +1016,12 @@ mod tests { match iter.next().expect("ip address") { Protocol::Ip4(ip) => assert!(!ip.is_unspecified()), Protocol::Ip6(ip) => assert!(!ip.is_unspecified()), - other => panic!("Unexpected protocol: {}", other), + other => panic!("Unexpected protocol: {other}"), } if let Protocol::Tcp(port) = iter.next().expect("port") { assert_ne!(0, port) } else { - panic!("No TCP port in address: {}", listen_addr) + panic!("No TCP port in address: {listen_addr}") } ready_tx.send(listen_addr).await.ok(); } @@ -1103,7 +1103,7 @@ mod tests { upgrade.write_all(&[4, 5, 6]).await.unwrap(); return; } - e => panic!("Unexpected event: {:?}", e), + e => panic!("Unexpected event: {e:?}"), } } } @@ -1140,7 +1140,7 @@ mod tests { socket.read_exact(&mut buf).await.unwrap(); assert_eq!(buf, [4, 5, 6]); } - e => panic!("Unexpected transport event: {:?}", e), + e => panic!("Unexpected transport event: {e:?}"), } } @@ -1203,10 +1203,10 @@ mod tests { TransportEvent::NewAddress { listen_addr: addr2, .. } => assert_eq!(addr1, addr2), - e => panic!("Unexpected transport event: {:?}", e), + e => panic!("Unexpected transport event: {e:?}"), } } - e => panic!("Unexpected transport event: {:?}", e), + e => panic!("Unexpected transport event: {e:?}"), } } diff --git a/transports/tls/src/certificate.rs b/transports/tls/src/certificate.rs index 43d9c846..d5a5bf89 100644 --- a/transports/tls/src/certificate.rs +++ b/transports/tls/src/certificate.rs @@ -519,7 +519,7 @@ mod tests { let error = parse(&certificate).unwrap_err(); - assert_eq!(format!("{}", error), "UnknownIssuer"); + assert_eq!(format!("{error}"), "UnknownIssuer"); } #[test] diff --git a/transports/tls/src/verifier.rs b/transports/tls/src/verifier.rs index 05d38068..b6378d65 100644 --- a/transports/tls/src/verifier.rs +++ b/transports/tls/src/verifier.rs @@ -238,7 +238,7 @@ impl From for rustls::Error { use webpki::Error::*; match e { BadDer => rustls::Error::InvalidCertificateEncoding, - e => rustls::Error::InvalidCertificateData(format!("invalid peer certificate: {}", e)), + e => rustls::Error::InvalidCertificateData(format!("invalid peer certificate: {e}")), } } } @@ -250,7 +250,7 @@ impl From for rustls::Error { UnsupportedSignatureAlgorithm | UnsupportedSignatureAlgorithmForPublicKey => { rustls::Error::InvalidCertificateSignatureType } - e => rustls::Error::InvalidCertificateData(format!("invalid peer certificate: {}", e)), + e => rustls::Error::InvalidCertificateData(format!("invalid peer certificate: {e}")), } } } diff --git a/transports/tls/tests/smoke.rs b/transports/tls/tests/smoke.rs index 1d49fd5c..37be61c0 100644 --- a/transports/tls/tests/smoke.rs +++ b/transports/tls/tests/smoke.rs @@ -30,7 +30,7 @@ async fn can_establish_connection() { match swarm1.next().await.unwrap() { SwarmEvent::ConnectionEstablished { peer_id, .. } => break peer_id, SwarmEvent::IncomingConnectionError { error, .. } => { - panic!("Incoming connection failed: {}", error) + panic!("Incoming connection failed: {error}") } _ => continue, }; @@ -41,7 +41,7 @@ async fn can_establish_connection() { match swarm2.next().await.unwrap() { SwarmEvent::ConnectionEstablished { peer_id, .. } => break peer_id, SwarmEvent::OutgoingConnectionError { error, .. } => { - panic!("Failed to dial: {}", error) + panic!("Failed to dial: {error}") } _ => continue, }; diff --git a/transports/wasm-ext/src/lib.rs b/transports/wasm-ext/src/lib.rs index 5ed34f41..164cbff4 100644 --- a/transports/wasm-ext/src/lib.rs +++ b/transports/wasm-ext/src/lib.rs @@ -631,14 +631,14 @@ impl From for io::Error { impl fmt::Debug for JsErr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self) + write!(f, "{self}") } } impl fmt::Display for JsErr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(s) = self.0.as_string() { - write!(f, "{}", s) + write!(f, "{s}") } else if let Some(err) = self.0.dyn_ref::() { write!(f, "{}", String::from(err.message())) } else if let Some(obj) = self.0.dyn_ref::() { diff --git a/transports/webrtc/src/tokio/fingerprint.rs b/transports/webrtc/src/tokio/fingerprint.rs index 55cfa1d5..8a03044c 100644 --- a/transports/webrtc/src/tokio/fingerprint.rs +++ b/transports/webrtc/src/tokio/fingerprint.rs @@ -83,7 +83,7 @@ impl Fingerprint { /// /// This is the format described in . pub fn to_sdp_format(self) -> String { - self.0.map(|byte| format!("{:02X}", byte)).join(":") + self.0.map(|byte| format!("{byte:02X}")).join(":") } /// Returns the algorithm used (e.g. "sha-256"). diff --git a/transports/webrtc/src/tokio/transport.rs b/transports/webrtc/src/tokio/transport.rs index 5d43674f..0ace3cbb 100644 --- a/transports/webrtc/src/tokio/transport.rs +++ b/transports/webrtc/src/tokio/transport.rs @@ -598,7 +598,7 @@ mod tests { ); assert!(matches!(listen_addr.iter().nth(2), Some(Protocol::WebRTC))); } - e => panic!("Unexpected event: {:?}", e), + e => panic!("Unexpected event: {e:?}"), } assert!( transport.remove_listener(listener), @@ -611,7 +611,7 @@ mod tests { } => { assert_eq!(listener_id, listener); } - e => panic!("Unexpected event: {:?}", e), + e => panic!("Unexpected event: {e:?}"), } // Poll once again so that the listener has the chance to return `Poll::Ready(None)` and // be removed from the list of listeners. diff --git a/transports/webrtc/src/tokio/udp_mux.rs b/transports/webrtc/src/tokio/udp_mux.rs index 8a18ec64..de0b31c6 100644 --- a/transports/webrtc/src/tokio/udp_mux.rs +++ b/transports/webrtc/src/tokio/udp_mux.rs @@ -537,10 +537,7 @@ fn ufrag_from_stun_message(buffer: &[u8], local_ufrag: bool) -> Result Result Err(Error::Other(format!( - "failed to decode USERNAME from STUN message as UTF-8: {}", - err + "failed to decode USERNAME from STUN message as UTF-8: {err}" ))), Ok(s) => { // s is a combination of the local_ufrag and the remote ufrag separated by `:`. diff --git a/transports/webrtc/tests/smoke.rs b/transports/webrtc/tests/smoke.rs index 68821dcd..26779d13 100644 --- a/transports/webrtc/tests/smoke.rs +++ b/transports/webrtc/tests/smoke.rs @@ -83,7 +83,7 @@ async fn start_listening(transport: &mut Boxed<(PeerId, StreamMuxerBox)>, addr: transport.listen_on(addr.parse().unwrap()).unwrap(); match transport.next().await { Some(TransportEvent::NewAddress { listen_addr, .. }) => listen_addr, - e => panic!("{:?}", e), + e => panic!("{e:?}"), } } diff --git a/transports/websocket/src/error.rs b/transports/websocket/src/error.rs index 47421d4c..7dc22331 100644 --- a/transports/websocket/src/error.rs +++ b/transports/websocket/src/error.rs @@ -44,13 +44,13 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Error::Transport(err) => write!(f, "{}", err), - Error::Tls(err) => write!(f, "{}", err), - Error::Handshake(err) => write!(f, "{}", err), - Error::InvalidMultiaddr(ma) => write!(f, "invalid multi-address: {}", ma), + Error::Transport(err) => write!(f, "{err}"), + Error::Tls(err) => write!(f, "{err}"), + Error::Handshake(err) => write!(f, "{err}"), + Error::InvalidMultiaddr(ma) => write!(f, "invalid multi-address: {ma}"), Error::TooManyRedirects => f.write_str("too many redirects"), Error::InvalidRedirectLocation => f.write_str("invalid redirect location"), - Error::Base(err) => write!(f, "{}", err), + Error::Base(err) => write!(f, "{err}"), } } } diff --git a/transports/websocket/src/framed.rs b/transports/websocket/src/framed.rs index 65b4db93..0b069d27 100644 --- a/transports/websocket/src/framed.rs +++ b/transports/websocket/src/framed.rs @@ -381,7 +381,7 @@ where Ok(Either::Left(location)) } handshake::ServerResponse::Rejected { status_code } => { - let msg = format!("server rejected handshake; status code = {}", status_code); + let msg = format!("server rejected handshake; status code = {status_code}"); Err(Error::Handshake(msg.into())) } handshake::ServerResponse::Accepted { .. } => { @@ -501,10 +501,10 @@ fn parse_ws_dial_addr(addr: Multiaddr) -> Result> { let (host_port, dns_name) = loop { match (ip, tcp) { (Some(Protocol::Ip4(ip)), Some(Protocol::Tcp(port))) => { - break (format!("{}:{}", ip, port), None) + break (format!("{ip}:{port}"), None) } (Some(Protocol::Ip6(ip)), Some(Protocol::Tcp(port))) => { - break (format!("{}:{}", ip, port), None) + break (format!("{ip}:{port}"), None) } (Some(Protocol::Dns(h)), Some(Protocol::Tcp(port))) | (Some(Protocol::Dns4(h)), Some(Protocol::Tcp(port))) diff --git a/transports/websocket/src/tls.rs b/transports/websocket/src/tls.rs index 89b6a85e..260031ea 100644 --- a/transports/websocket/src/tls.rs +++ b/transports/websocket/src/tls.rs @@ -167,9 +167,9 @@ pub enum Error { impl fmt::Display for Error { 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), - Error::InvalidDnsName(n) => write!(f, "invalid DNS name: {}", n), + Error::Io(e) => write!(f, "i/o error: {e}"), + Error::Tls(e) => write!(f, "tls error: {e}"), + Error::InvalidDnsName(n) => write!(f, "invalid DNS name: {n}"), } } }