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.
This commit is contained in:
Hannes 2022-12-14 16:45:04 +01:00 committed by GitHub
parent be3ec6c62b
commit d79c93abdb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
72 changed files with 244 additions and 307 deletions

View File

@ -218,7 +218,7 @@ impl fmt::Debug for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("PublicKey(asn.1 uncompressed): ")?; f.write_str("PublicKey(asn.1 uncompressed): ")?;
for byte in &self.encode_der() { for byte in &self.encode_der() {
write!(f, "{:x}", byte)?; write!(f, "{byte:x}")?;
} }
Ok(()) Ok(())
} }

View File

@ -122,7 +122,7 @@ impl fmt::Debug for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("PublicKey(compressed): ")?; f.write_str("PublicKey(compressed): ")?;
for byte in self.0.as_bytes() { for byte in self.0.as_bytes() {
write!(f, "{:x}", byte)?; write!(f, "{byte:x}")?;
} }
Ok(()) Ok(())
} }

View File

@ -120,7 +120,7 @@ impl fmt::Debug for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("PublicKey(PKCS1): ")?; f.write_str("PublicKey(PKCS1): ")?;
for byte in &self.0 { for byte in &self.0 {
write!(f, "{:x}", byte)?; write!(f, "{byte:x}")?;
} }
Ok(()) Ok(())
} }

View File

@ -158,7 +158,7 @@ impl fmt::Debug for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("PublicKey(compressed): ")?; f.write_str("PublicKey(compressed): ")?;
for byte in &self.encode() { for byte in &self.encode() {
write!(f, "{:x}", byte)?; write!(f, "{byte:x}")?;
} }
Ok(()) Ok(())
} }

View File

@ -168,8 +168,7 @@ impl fmt::Display for ReadPayloadError {
Self::InvalidSignature => write!(f, "Invalid signature"), Self::InvalidSignature => write!(f, "Invalid signature"),
Self::UnexpectedPayloadType { expected, got } => write!( Self::UnexpectedPayloadType { expected, got } => write!(
f, f,
"Unexpected payload type, expected {:?} but got {:?}", "Unexpected payload type, expected {expected:?} but got {got:?}"
expected, got
), ),
} }
} }

View File

@ -541,7 +541,7 @@ where
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
TransportError::MultiaddrNotSupported(addr) => { TransportError::MultiaddrNotSupported(addr) => {
write!(f, "Multiaddr is not supported: {}", addr) write!(f, "Multiaddr is not supported: {addr}")
} }
TransportError::Other(_) => Ok(()), TransportError::Other(_) => Ok(()),
} }

View File

@ -500,7 +500,7 @@ mod tests {
#[test] #[test]
fn stop_listening() { fn stop_listening() {
let rand_port = rand::random::<u64>().saturating_add(1); let rand_port = rand::random::<u64>().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(); let mut transport = MemoryTransport::default().boxed();
futures::executor::block_on(async { futures::executor::block_on(async {
@ -520,7 +520,7 @@ mod tests {
assert_eq!(id, listener_id); assert_eq!(id, listener_id);
assert!(reason.is_ok()) assert!(reason.is_ok())
} }
other => panic!("Unexpected transport event: {:?}", other), other => panic!("Unexpected transport event: {other:?}"),
} }
assert!(!transport.remove_listener(listener_id)); assert!(!transport.remove_listener(listener_id));
}) })
@ -533,7 +533,7 @@ mod tests {
// Setup listener. // Setup listener.
let rand_port = rand::random::<u64>().saturating_add(1); let rand_port = rand::random::<u64>().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 cloned_t1_addr = t1_addr.clone();
let mut t1 = MemoryTransport::default().boxed(); let mut t1 = MemoryTransport::default().boxed();

View File

@ -198,8 +198,8 @@ where
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
TransportTimeoutError::Timeout => write!(f, "Timeout has been reached"), TransportTimeoutError::Timeout => write!(f, "Timeout has been reached"),
TransportTimeoutError::TimerError(err) => write!(f, "Error in the timer: {}", err), TransportTimeoutError::TimerError(err) => write!(f, "Error in the timer: {err}"),
TransportTimeoutError::Other(err) => write!(f, "{}", err), TransportTimeoutError::Other(err) => write!(f, "{err}"),
} }
} }
} }

View File

@ -471,8 +471,8 @@ where
{ {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
TransportUpgradeError::Transport(e) => write!(f, "Transport error: {}", e), TransportUpgradeError::Transport(e) => write!(f, "Transport error: {e}"),
TransportUpgradeError::Upgrade(e) => write!(f, "Upgrade error: {}", e), TransportUpgradeError::Upgrade(e) => write!(f, "Upgrade error: {e}"),
} }
} }
} }

View File

@ -113,10 +113,7 @@ pub async fn read_length_prefixed(
if len > max_size { if len > max_size {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
format!( format!("Received data size ({len} bytes) exceeds maximum ({max_size} bytes)"),
"Received data size ({} bytes) exceeds maximum ({} bytes)",
len, max_size
),
)); ));
} }

View File

@ -103,10 +103,7 @@ fn strip_peer_id(addr: &mut Multiaddr) {
Some(Protocol::P2p(peer_id)) => { Some(Protocol::P2p(peer_id)) => {
let mut addr = Multiaddr::empty(); let mut addr = Multiaddr::empty();
addr.push(Protocol::P2p(peer_id)); addr.push(Protocol::P2p(peer_id));
println!( println!("removing peer id {addr} so this address can be dialed by rust-libp2p");
"removing peer id {} so this address can be dialed by rust-libp2p",
addr
);
} }
Some(other) => addr.push(other), Some(other) => addr.push(other),
_ => {} _ => {}

View File

@ -71,13 +71,13 @@ fn main() -> Result<(), Box<dyn Error>> {
Command::Rand { prefix } => { Command::Rand { prefix } => {
if let Some(prefix) = prefix { if let Some(prefix) = prefix {
if prefix.as_bytes().iter().any(|c| !ALPHABET.contains(c)) { 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); std::process::exit(1);
} }
// Checking conformity to ALLOWED_FIRST_BYTE. // Checking conformity to ALLOWED_FIRST_BYTE.
if !prefix.is_empty() && !ALLOWED_FIRST_BYTE.contains(&prefix.as_bytes()[0]) { 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!( eprintln!(
"Only the following bytes are possible as first byte: {}", "Only the following bytes are possible as first byte: {}",
str::from_utf8(ALLOWED_FIRST_BYTE).unwrap() str::from_utf8(ALLOWED_FIRST_BYTE).unwrap()

View File

@ -378,7 +378,7 @@ impl fmt::Display for NegotiationError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self { match self {
NegotiationError::ProtocolError(p) => { 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."), NegotiationError::Failed => fmt.write_str("Protocol negotiation failed."),
} }

View File

@ -443,7 +443,7 @@ impl Error for ProtocolError {
impl fmt::Display for ProtocolError { impl fmt::Display for ProtocolError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self { 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::InvalidMessage => write!(fmt, "Received an invalid message."),
ProtocolError::InvalidProtocol => write!(fmt, "A protocol (name) is invalid."), ProtocolError::InvalidProtocol => write!(fmt, "A protocol (name) is invalid."),
ProtocolError::TooManyProtocols => write!(fmt, "Too many protocols received."), ProtocolError::TooManyProtocols => write!(fmt, "Too many protocols received."),
@ -465,7 +465,7 @@ mod tests {
.filter(|&c| c.is_ascii_alphanumeric()) .filter(|&c| c.is_ascii_alphanumeric())
.take(n) .take(n)
.collect(); .collect();
Protocol(Bytes::from(format!("/{}", p))) Protocol(Bytes::from(format!("/{p}")))
} }
} }
@ -487,10 +487,10 @@ mod tests {
fn prop(msg: Message) { fn prop(msg: Message) {
let mut buf = BytesMut::new(); let mut buf = BytesMut::new();
msg.encode(&mut buf) 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()) { match Message::decode(buf.freeze()) {
Ok(m) => assert_eq!(m, msg), Ok(m) => assert_eq!(m, msg),
Err(e) => panic!("Decoding failed: {:?}", e), Err(e) => panic!("Decoding failed: {e:?}"),
} }
} }
quickcheck(prop as fn(_)) quickcheck(prop as fn(_))

View File

@ -92,7 +92,7 @@ fn negotiation_failed() {
Ok((_, io)) => io, Ok((_, io)) => io,
Err(NegotiationError::Failed) => return, Err(NegotiationError::Failed) => return,
Err(NegotiationError::ProtocolError(e)) => { Err(NegotiationError::ProtocolError(e)) => {
panic!("Unexpected protocol error {}", e) panic!("Unexpected protocol error {e}")
} }
}; };
match io.complete().await { match io.complete().await {

View File

@ -60,7 +60,7 @@ fn prepare(c: &mut Criterion) {
tcp.throughput(Throughput::Bytes(payload.len() as u64)); tcp.throughput(Throughput::Bytes(payload.len() as u64));
let mut receiver_transport = tcp_transport(size); let mut receiver_transport = tcp_transport(size);
let mut sender_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(|| { b.iter(|| {
run( run(
black_box(&mut receiver_transport), black_box(&mut receiver_transport),
@ -79,7 +79,7 @@ fn prepare(c: &mut Criterion) {
mem.throughput(Throughput::Bytes(payload.len() as u64)); mem.throughput(Throughput::Bytes(payload.len() as u64));
let mut receiver_transport = mem_transport(size); let mut receiver_transport = mem_transport(size);
let mut sender_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(|| { b.iter(|| {
run( run(
black_box(&mut receiver_transport), black_box(&mut receiver_transport),

View File

@ -205,7 +205,7 @@ impl Decoder for Codec {
CodecDecodeState::HasHeader(header) => match self.varint_decoder.decode(src)? { CodecDecodeState::HasHeader(header) => match self.varint_decoder.decode(src)? {
Some(len) => { Some(len) => {
if len as usize > MAX_FRAME_SIZE { 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)); return Err(io::Error::new(io::ErrorKind::InvalidData, msg));
} }
@ -252,7 +252,7 @@ impl Decoder for Codec {
stream_id: RemoteStreamId::dialer(num), 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)); return Err(io::Error::new(io::ErrorKind::InvalidData, msg));
} }
}; };

View File

@ -1220,7 +1220,7 @@ mod tests {
for i in 0..cfg.max_substreams { for i in 0..cfg.max_substreams {
match m.poll_next_stream(cx) { match m.poll_next_stream(cx) {
Poll::Pending => panic!("Expected new inbound stream."), Poll::Pending => panic!("Expected new inbound stream."),
Poll::Ready(Err(e)) => panic!("{:?}", e), Poll::Ready(Err(e)) => panic!("{e:?}"),
Poll::Ready(Ok(id)) => { Poll::Ready(Ok(id)) => {
assert_eq!(id, LocalStreamId::listener(i as u64)); assert_eq!(id, LocalStreamId::listener(i as u64));
} }
@ -1231,7 +1231,7 @@ mod tests {
// after reading and buffering data frames up to the limit. // after reading and buffering data frames up to the limit.
let id = LocalStreamId::listener(0); let id = LocalStreamId::listener(0);
match m.poll_next_stream(cx) { 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 => { Poll::Pending => {
// We expect the implementation to yield when the buffer // We expect the implementation to yield when the buffer
// is full but before it is exceeded and the max buffer // is full but before it is exceeded and the max buffer
@ -1243,7 +1243,7 @@ mod tests {
cfg.max_buffer_len cfg.max_buffer_len
); );
match m.poll_next_stream(cx) { 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 => { Poll::Pending => {
// Expect the buffer for stream 0 to be exceeded, triggering // Expect the buffer for stream 0 to be exceeded, triggering
// the max. buffer behaviour. // the max. buffer behaviour.
@ -1281,7 +1281,7 @@ mod tests {
Poll::Ready(Ok(Some(bytes))) => { Poll::Ready(Ok(Some(bytes))) => {
assert_eq!(bytes, data); assert_eq!(bytes, data);
} }
x => panic!("Unexpected: {:?}", x), x => panic!("Unexpected: {x:?}"),
} }
} }
@ -1293,7 +1293,7 @@ mod tests {
// Expect to read EOF // Expect to read EOF
match m.poll_read_stream(cx, id) { match m.poll_read_stream(cx, id) {
Poll::Ready(Ok(None)) => {} Poll::Ready(Ok(None)) => {}
poll => panic!("Unexpected: {:?}", poll), poll => panic!("Unexpected: {poll:?}"),
} }
} }
MaxBufferBehaviour::Block => { MaxBufferBehaviour::Block => {
@ -1301,7 +1301,7 @@ mod tests {
match m.poll_read_stream(cx, id) { match m.poll_read_stream(cx, id) {
Poll::Ready(Ok(Some(bytes))) => assert_eq!(bytes, data), Poll::Ready(Ok(Some(bytes))) => assert_eq!(bytes, data),
Poll::Pending => assert_eq!(overflow.get(), 1), Poll::Pending => assert_eq!(overflow.get(), 1),
poll => panic!("Unexpected: {:?}", poll), poll => panic!("Unexpected: {poll:?}"),
} }
} }
} }

View File

@ -64,7 +64,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let local_key = identity::Keypair::generate_ed25519(); let local_key = identity::Keypair::generate_ed25519();
let local_peer_id = PeerId::from(local_key.public()); 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() let transport = tcp::async_io::Transport::default()
.upgrade(Version::V1) .upgrade(Version::V1)
@ -88,9 +88,9 @@ async fn main() -> Result<(), Box<dyn Error>> {
loop { loop {
match swarm.select_next_some().await { match swarm.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {:?}", address), SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {address:?}"),
SwarmEvent::Behaviour(event) => println!("{:?}", event), SwarmEvent::Behaviour(event) => println!("{event:?}"),
e => println!("{:?}", e), e => println!("{e:?}"),
} }
} }
} }

View File

@ -53,7 +53,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let local_key = identity::Keypair::generate_ed25519(); let local_key = identity::Keypair::generate_ed25519();
let local_peer_id = PeerId::from(local_key.public()); 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() let transport = tcp::async_io::Transport::default()
.upgrade(Version::V1) .upgrade(Version::V1)
@ -72,9 +72,9 @@ async fn main() -> Result<(), Box<dyn Error>> {
loop { loop {
match swarm.select_next_some().await { match swarm.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {:?}", address), SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {address:?}"),
SwarmEvent::Behaviour(event) => println!("{:?}", event), SwarmEvent::Behaviour(event) => println!("{event:?}"),
e => println!("{:?}", e), e => println!("{e:?}"),
} }
} }
} }

View File

@ -122,7 +122,7 @@ async fn test_auto_probe() {
assert!(peer.is_none()); assert!(peer.is_none());
assert_eq!(error, OutboundProbeError::NoAddresses); 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); assert_eq!(client.behaviour().nat_status(), NatStatus::Unknown);
@ -140,7 +140,7 @@ async fn test_auto_probe() {
assert_eq!(peer, server_id); assert_eq!(peer, server_id);
probe_id probe_id
} }
other => panic!("Unexpected behaviour event: {:?}.", other), other => panic!("Unexpected behaviour event: {other:?}."),
}; };
match next_event(&mut client).await { match next_event(&mut client).await {
@ -156,7 +156,7 @@ async fn test_auto_probe() {
OutboundProbeError::Response(ResponseError::DialError) OutboundProbeError::Response(ResponseError::DialError)
); );
} }
other => panic!("Unexpected behaviour event: {:?}.", other), other => panic!("Unexpected behaviour event: {other:?}."),
} }
match next_event(&mut client).await { match next_event(&mut client).await {
@ -164,7 +164,7 @@ async fn test_auto_probe() {
assert_eq!(old, NatStatus::Unknown); assert_eq!(old, NatStatus::Unknown);
assert_eq!(new, NatStatus::Private); assert_eq!(new, NatStatus::Private);
} }
other => panic!("Unexpected behaviour event: {:?}.", other), other => panic!("Unexpected behaviour event: {other:?}."),
} }
assert_eq!(client.behaviour().confidence(), 0); assert_eq!(client.behaviour().confidence(), 0);
@ -186,7 +186,7 @@ async fn test_auto_probe() {
assert_eq!(peer, server_id); assert_eq!(peer, server_id);
probe_id probe_id
} }
other => panic!("Unexpected behaviour event: {:?}.", other), other => panic!("Unexpected behaviour event: {other:?}."),
}; };
let mut had_connection_event = false; let mut had_connection_event = false;
@ -216,7 +216,7 @@ async fn test_auto_probe() {
SwarmEvent::IncomingConnection { .. } SwarmEvent::IncomingConnection { .. }
| SwarmEvent::NewListenAddr { .. } | SwarmEvent::NewListenAddr { .. }
| SwarmEvent::ExpiredListenAddr { .. } => {} | 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() => { } if endpoint.is_listener() => {
assert_eq!(peer_id, server_id); 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); assert_eq!(peer, server_id);
probe_id probe_id
} }
other => panic!("Unexpected behaviour event: {:?}.", other), other => panic!("Unexpected behaviour event: {other:?}."),
}; };
match next_event(&mut client).await { match next_event(&mut client).await {
@ -302,12 +302,12 @@ async fn test_confidence() {
); );
(peer.unwrap(), probe_id) (peer.unwrap(), probe_id)
} }
other => panic!("Unexpected Outbound Event: {:?}", other), other => panic!("Unexpected Outbound Event: {other:?}"),
}; };
assert_eq!(peer, server_id); assert_eq!(peer, server_id);
assert_eq!(probe_id, 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 // Confidence should increase each iteration up to MAX_CONFIDENCE
@ -326,7 +326,7 @@ async fn test_confidence() {
assert_eq!(old, NatStatus::Unknown); assert_eq!(old, NatStatus::Unknown);
assert_eq!(new.is_public(), test_public); 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::Request { .. }) => {}
Event::OutboundProbe(OutboundProbeEvent::Response { .. }) => {} 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!(peer.is_none());
assert_eq!(error, OutboundProbeError::NoServer); assert_eq!(error, OutboundProbeError::NoServer);
} }
other => panic!("Unexpected behaviour event: {:?}.", other), other => panic!("Unexpected behaviour event: {other:?}."),
} }
assert_eq!(client.behaviour().confidence(), 0); assert_eq!(client.behaviour().confidence(), 0);
}; };
@ -431,14 +431,14 @@ async fn test_use_connected_as_server() {
Event::OutboundProbe(OutboundProbeEvent::Request { peer, .. }) => { Event::OutboundProbe(OutboundProbeEvent::Request { peer, .. }) => {
assert_eq!(peer, server_id); assert_eq!(peer, server_id);
} }
other => panic!("Unexpected behaviour event: {:?}.", other), other => panic!("Unexpected behaviour event: {other:?}."),
} }
match next_event(&mut client).await { match next_event(&mut client).await {
Event::OutboundProbe(OutboundProbeEvent::Response { peer, .. }) => { Event::OutboundProbe(OutboundProbeEvent::Response { peer, .. }) => {
assert_eq!(peer, server_id); 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::Request { .. }) => {}
Event::OutboundProbe(OutboundProbeEvent::Response { .. }) => {} 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)); 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, .. }) => { Event::OutboundProbe(OutboundProbeEvent::Error { error, .. }) => {
assert!(matches!(error, OutboundProbeError::NoServer)) assert!(matches!(error, OutboundProbeError::NoServer))
} }
other => panic!("Unexpected behaviour event: {:?}.", other), other => panic!("Unexpected behaviour event: {other:?}."),
} }
}; };

View File

@ -167,7 +167,7 @@ async fn test_dial_back() {
SwarmEvent::IncomingConnection { .. } SwarmEvent::IncomingConnection { .. }
| SwarmEvent::NewListenAddr { .. } | SwarmEvent::NewListenAddr { .. }
| SwarmEvent::ExpiredListenAddr { .. } => {} | SwarmEvent::ExpiredListenAddr { .. } => {}
other => panic!("Unexpected swarm event: {:?}.", other), other => panic!("Unexpected swarm event: {other:?}."),
} }
}; };
let expect_addr = Multiaddr::empty() let expect_addr = Multiaddr::empty()
@ -185,7 +185,7 @@ async fn test_dial_back() {
assert_eq!(addresses[0], expect_addr); assert_eq!(addresses[0], expect_addr);
probe_id probe_id
} }
other => panic!("Unexpected behaviour event: {:?}.", other), other => panic!("Unexpected behaviour event: {other:?}."),
}; };
loop { loop {
@ -209,7 +209,7 @@ async fn test_dial_back() {
} }
SwarmEvent::Dialing(peer) => assert_eq!(peer, client_id), SwarmEvent::Dialing(peer) => assert_eq!(peer, client_id),
SwarmEvent::NewListenAddr { .. } | SwarmEvent::ExpiredListenAddr { .. } => {} 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!(peer, client_id);
assert_eq!(address, expect_addr); 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); assert_eq!(peer, client_id);
probe_id probe_id
} }
other => panic!("Unexpected behaviour event: {:?}.", other), other => panic!("Unexpected behaviour event: {other:?}."),
}; };
loop { loop {
@ -253,7 +253,7 @@ async fn test_dial_error() {
} }
SwarmEvent::Dialing(peer) => assert_eq!(peer, client_id), SwarmEvent::Dialing(peer) => assert_eq!(peer, client_id),
SwarmEvent::NewListenAddr { .. } | SwarmEvent::ExpiredListenAddr { .. } => {} 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!(peer, client_id);
assert_eq!(error, InboundProbeError::Response(ResponseError::DialError)); 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, .. }) => { Event::InboundProbe(InboundProbeEvent::Request { peer, probe_id, .. }) => {
(probe_id, peer) (probe_id, peer)
} }
other => panic!("Unexpected behaviour event: {:?}.", other), other => panic!("Unexpected behaviour event: {other:?}."),
}; };
loop { loop {
@ -313,7 +313,7 @@ async fn test_throttle_global_max() {
assert_eq!(first_peer_id, peer); assert_eq!(first_peer_id, peer);
assert_eq!(first_probe_id, probe_id); 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); assert_eq!(client_id, peer);
probe_id probe_id
} }
other => panic!("Unexpected behaviour event: {:?}.", other), other => panic!("Unexpected behaviour event: {other:?}."),
}; };
match next_event(&mut server).await { match next_event(&mut server).await {
@ -348,7 +348,7 @@ async fn test_throttle_peer_max() {
assert_eq!(peer, client_id); assert_eq!(peer, client_id);
assert_eq!(probe_id, first_probe_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 { match next_event(&mut server).await {
@ -364,7 +364,7 @@ async fn test_throttle_peer_max() {
InboundProbeError::Response(ResponseError::DialRefused) 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); assert_eq!(client_id, peer);
addresses addresses
} }
other => panic!("Unexpected behaviour event: {:?}.", other), other => panic!("Unexpected behaviour event: {other:?}."),
}; };
loop { loop {
@ -417,7 +417,7 @@ async fn test_dial_multiple_addr() {
} }
SwarmEvent::Dialing(peer) => assert_eq!(peer, client_id), SwarmEvent::Dialing(peer) => assert_eq!(peer, client_id),
SwarmEvent::NewListenAddr { .. } | SwarmEvent::ExpiredListenAddr { .. } => {} 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, error,
InboundProbeError::Response(ResponseError::DialRefused) InboundProbeError::Response(ResponseError::DialRefused)
)), )),
other => panic!("Unexpected behaviour event: {:?}.", other), other => panic!("Unexpected behaviour event: {other:?}."),
}; };
}; };

View File

@ -185,7 +185,7 @@ fn main() -> Result<(), Box<dyn Error>> {
SwarmEvent::NewListenAddr { address, .. } => { SwarmEvent::NewListenAddr { address, .. } => {
info!("Listening on {:?}", address); info!("Listening on {:?}", address);
} }
event => panic!("{:?}", event), event => panic!("{event:?}"),
} }
} }
_ = delay => { _ = delay => {
@ -220,7 +220,7 @@ fn main() -> Result<(), Box<dyn Error>> {
info!("Relay told us our public address: {:?}", observed_addr); info!("Relay told us our public address: {:?}", observed_addr);
learned_observed_addr = true; learned_observed_addr = true;
} }
event => panic!("{:?}", event), event => panic!("{event:?}"),
} }
if learned_observed_addr && told_relay_observed_addr { if learned_observed_addr && told_relay_observed_addr {

View File

@ -83,7 +83,7 @@ fn connect() {
remote_peer_id, remote_peer_id,
remote_relayed_addr, remote_relayed_addr,
} if remote_peer_id == dst_peer_id && remote_relayed_addr == dst_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( pool.run_until(wait_for_connection_established(
&mut src, &mut src,
@ -210,7 +210,7 @@ async fn wait_for_reservation(
} }
SwarmEvent::Dialing(peer_id) if peer_id == relay_peer_id => {} SwarmEvent::Dialing(peer_id) if peer_id == relay_peer_id => {}
SwarmEvent::ConnectionEstablished { 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<Client>, addr: &Mult
client::Event::OutboundCircuitEstablished { .. }, client::Event::OutboundCircuitEstablished { .. },
)) => {} )) => {}
SwarmEvent::ConnectionEstablished { .. } => {} SwarmEvent::ConnectionEstablished { .. } => {}
e => panic!("{:?}", e), e => panic!("{e:?}"),
} }
} }
} }
@ -237,7 +237,7 @@ async fn wait_for_connection_established(client: &mut Swarm<Client>, addr: &Mult
async fn wait_for_new_listen_addr(client: &mut Swarm<Client>, new_addr: &Multiaddr) { async fn wait_for_new_listen_addr(client: &mut Swarm<Client>, new_addr: &Multiaddr) {
match client.select_next_some().await { match client.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } if address == *new_addr => {} 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<Client>) -> dcutr::behaviour::E
loop { loop {
match client.select_next_some().await { match client.select_next_some().await {
SwarmEvent::Behaviour(ClientEvent::Dcutr(e)) => return e, SwarmEvent::Behaviour(ClientEvent::Dcutr(e)) => return e,
e => panic!("{:?}", e), e => panic!("{e:?}"),
} }
} }
} }

View File

@ -4767,8 +4767,8 @@ fn test_iwant_penalties() {
assert!(i > 9); assert!(i > 9);
double_penalized += 1 double_penalized += 1
} else { } else {
println!("{}", peer); println!("{peer}");
println!("{}", score); println!("{score}");
panic!("Invalid score of peer"); panic!("Invalid score of peer");
} }
} }

View File

@ -42,7 +42,7 @@ pub enum PublishError {
impl std::fmt::Display for PublishError { impl std::fmt::Display for PublishError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 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 { impl std::fmt::Display for SubscriptionError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 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 { impl std::fmt::Display for ValidationError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self) write!(f, "{self:?}")
} }
} }

View File

@ -174,10 +174,7 @@ impl PeerScoreParams {
pub fn validate(&self) -> Result<(), String> { pub fn validate(&self) -> Result<(), String> {
for (topic, params) in self.topics.iter() { for (topic, params) in self.topics.iter() {
if let Err(e) = params.validate() { if let Err(e) = params.validate() {
return Err(format!( return Err(format!("Invalid score parameters for topic {topic}: {e}"));
"Invalid score parameters for topic {}: {}",
topic, e
));
} }
} }

View File

@ -100,8 +100,7 @@ fn test_score_time_in_mesh() {
let score = peer_score.score(&peer_id); let score = peer_score.score(&peer_id);
assert!( assert!(
score == 0.0, score == 0.0,
"expected score to start at zero. Score found: {}", "expected score to start at zero. Score found: {score}"
score
); );
// The time in mesh depends on how long the peer has been grafted // 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; * (elapsed.as_millis() / topic_params.time_in_mesh_quantum.as_millis()) as f64;
assert!( assert!(
score >= expected, score >= expected,
"The score: {} should be greater than or equal to: {}", "The score: {score} should be greater than or equal to: {expected}"
score,
expected
); );
} }
@ -148,8 +145,7 @@ fn test_score_time_in_mesh_cap() {
let score = peer_score.score(&peer_id); let score = peer_score.score(&peer_id);
assert!( assert!(
score == 0.0, score == 0.0,
"expected score to start at zero. Score found: {}", "expected score to start at zero. Score found: {score}"
score
); );
// The time in mesh depends on how long the peer has been grafted // 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 score = peer_score.score(&peer_id);
let expected = let expected =
topic_params.topic_weight * topic_params.first_message_deliveries_weight * messages as f64; topic_params.topic_weight * topic_params.first_message_deliveries_weight * messages as f64;
assert!( assert!(score == expected, "The score: {score} should be {expected}");
score == expected,
"The score: {} should be {}",
score,
expected
);
} }
#[test] #[test]
@ -256,12 +247,7 @@ fn test_score_first_message_deliveries_cap() {
let expected = topic_params.topic_weight let expected = topic_params.topic_weight
* topic_params.first_message_deliveries_weight * topic_params.first_message_deliveries_weight
* topic_params.first_message_deliveries_cap; * topic_params.first_message_deliveries_cap;
assert!( assert!(score == expected, "The score: {score} should be {expected}");
score == expected,
"The score: {} should be {}",
score,
expected
);
} }
#[test] #[test]
@ -300,12 +286,7 @@ fn test_score_first_message_deliveries_decay() {
* topic_params.first_message_deliveries_weight * topic_params.first_message_deliveries_weight
* topic_params.first_message_deliveries_decay * topic_params.first_message_deliveries_decay
* messages as f64; * messages as f64;
assert!( assert!(score == expected, "The score: {score} should be {expected}");
score == expected,
"The score: {} should be {}",
score,
expected
);
// refreshing the scores applies the decay param // refreshing the scores applies the decay param
let decay_intervals = 10; let decay_intervals = 10;
@ -314,12 +295,7 @@ fn test_score_first_message_deliveries_decay() {
expected *= topic_params.first_message_deliveries_decay; expected *= topic_params.first_message_deliveries_decay;
} }
let score = peer_score.score(&peer_id); let score = peer_score.score(&peer_id);
assert!( assert!(score == expected, "The score: {score} should be {expected}");
score == expected,
"The score: {} should be {}",
score,
expected
);
} }
#[test] #[test]
@ -368,8 +344,7 @@ fn test_score_mesh_message_deliveries() {
let score = peer_score.score(peer_id); let score = peer_score.score(peer_id);
assert!( assert!(
score >= 0.0, score >= 0.0,
"expected no mesh delivery penalty before activation time, got score {}", "expected no mesh delivery penalty before activation time, got score {score}"
score
); );
} }
@ -402,13 +377,11 @@ fn test_score_mesh_message_deliveries() {
assert!( assert!(
score_a >= 0.0, score_a >= 0.0,
"expected non-negative score for Peer A, got score {}", "expected non-negative score for Peer A, got score {score_a}"
score_a
); );
assert!( assert!(
score_b >= 0.0, score_b >= 0.0,
"expected non-negative score for Peer B, got score {}", "expected non-negative score for Peer B, got score {score_b}"
score_b
); );
// the penalty is the difference between the threshold and the actual mesh deliveries, squared. // 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 = let expected =
topic_params.topic_weight * topic_params.mesh_message_deliveries_weight * penalty; topic_params.topic_weight * topic_params.mesh_message_deliveries_weight * penalty;
assert!( assert!(score_c == expected, "Score: {score_c}. Expected {expected}");
score_c == expected,
"Score: {}. Expected {}",
score_c,
expected
);
} }
#[test] #[test]
@ -469,8 +437,7 @@ fn test_score_mesh_message_deliveries_decay() {
let score_a = peer_score.score(&peer_id_a); let score_a = peer_score.score(&peer_id_a);
assert!( assert!(
score_a >= 0.0, score_a >= 0.0,
"expected non-negative score for Peer A, got score {}", "expected non-negative score for Peer A, got score {score_a}"
score_a
); );
let mut decayed_delivery_count = (messages as f64) * topic_params.mesh_message_deliveries_decay; 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); let score_b = peer_score.score(&peer_id_b);
assert!( assert!(
score_a >= 0.0, score_a >= 0.0,
"expected non-negative score for Peer A, got score {}", "expected non-negative score for Peer A, got score {score_a}"
score_a
); );
assert!( assert!(
score_b >= 0.0, score_b >= 0.0,
"expected non-negative score for Peer B, got score {}", "expected non-negative score for Peer B, got score {score_b}"
score_b
); );
// prune peer B to apply the penalty // prune peer B to apply the penalty

View File

@ -107,11 +107,11 @@ impl ProtocolId {
let protocol_id = match kind { let protocol_id = match kind {
PeerKind::Gossipsubv1_1 => match prefix { PeerKind::Gossipsubv1_1 => match prefix {
true => format!("/{}/{}", id, "1.1.0"), true => format!("/{}/{}", id, "1.1.0"),
false => format!("{}", id), false => format!("{id}"),
}, },
PeerKind::Gossipsub => match prefix { PeerKind::Gossipsub => match prefix {
true => format!("/{}/{}", id, "1.0.0"), true => format!("/{}/{}", id, "1.0.0"),
false => format!("{}", id), false => format!("{id}"),
}, },
PeerKind::Floodsub => format!("/{}/{}", "floodsub", "1.0.0"), PeerKind::Floodsub => format!("/{}/{}", "floodsub", "1.0.0"),
// NOTE: This is used for informing the behaviour of unsupported peers. We do not // NOTE: This is used for informing the behaviour of unsupported peers. We do not

View File

@ -354,7 +354,7 @@ mod test {
#[test] #[test]
fn test_filter_incoming_too_many_subscriptions() { fn test_filter_incoming_too_many_subscriptions() {
let t: Vec<_> = (0..4) let t: Vec<_> = (0..4)
.map(|i| TopicHash::from_raw(format!("t{}", i))) .map(|i| TopicHash::from_raw(format!("t{i}")))
.collect(); .collect();
let mut filter = MaxCountSubscriptionFilter { let mut filter = MaxCountSubscriptionFilter {
@ -383,7 +383,7 @@ mod test {
#[test] #[test]
fn test_filter_incoming_max_subscribed_valid() { fn test_filter_incoming_max_subscribed_valid() {
let t: Vec<_> = (0..5) let t: Vec<_> = (0..5)
.map(|i| TopicHash::from_raw(format!("t{}", i))) .map(|i| TopicHash::from_raw(format!("t{i}")))
.collect(); .collect();
let mut filter = MaxCountSubscriptionFilter { let mut filter = MaxCountSubscriptionFilter {

View File

@ -216,8 +216,7 @@ fn multi_hop_propagation() {
}); });
if !all_subscribed { if !all_subscribed {
return TestResult::error(format!( return TestResult::error(format!(
"Timed out waiting for all nodes to subscribe but only have {:?}/{:?}.", "Timed out waiting for all nodes to subscribe but only have {subscribed:?}/{num_nodes:?}.",
subscribed, num_nodes,
)); ));
} }
@ -246,8 +245,7 @@ fn multi_hop_propagation() {
}); });
if !all_received { if !all_received {
return TestResult::error(format!( return TestResult::error(format!(
"Timed out waiting for all nodes to receive the msg but only have {:?}/{:?}.", "Timed out waiting for all nodes to receive the msg but only have {received_msgs:?}/{num_nodes:?}.",
received_msgs, num_nodes,
)); ));
} }

View File

@ -47,7 +47,7 @@ use std::error::Error;
async fn main() -> Result<(), Box<dyn Error>> { async fn main() -> Result<(), Box<dyn Error>> {
let local_key = identity::Keypair::generate_ed25519(); let local_key = identity::Keypair::generate_ed25519();
let local_peer_id = PeerId::from(local_key.public()); 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() let transport = libp2p_tcp::async_io::Transport::default()
.upgrade(Version::V1) .upgrade(Version::V1)
@ -72,19 +72,19 @@ async fn main() -> Result<(), Box<dyn Error>> {
if let Some(addr) = std::env::args().nth(1) { if let Some(addr) = std::env::args().nth(1) {
let remote: Multiaddr = addr.parse()?; let remote: Multiaddr = addr.parse()?;
swarm.dial(remote)?; swarm.dial(remote)?;
println!("Dialed {}", addr) println!("Dialed {addr}")
} }
loop { loop {
match swarm.select_next_some().await { 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. // Prints peer id identify info is being sent to.
SwarmEvent::Behaviour(identify::Event::Sent { peer_id, .. }) => { 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 // Prints out the info received via the identify event
SwarmEvent::Behaviour(identify::Event::Received { info, .. }) => { SwarmEvent::Behaviour(identify::Event::Received { info, .. }) => {
println!("Received {:?}", info) println!("Received {info:?}")
} }
_ => {} _ => {}
} }

View File

@ -219,7 +219,7 @@ fn bootstrap() {
} }
// Ignore any other event. // Ignore any other event.
Poll::Ready(Some(_)) => (), Poll::Ready(Some(_)) => (),
e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"),
Poll::Pending => break, Poll::Pending => break,
} }
} }
@ -261,9 +261,9 @@ fn query_iter() {
assert_eq!(&key[..], search_target.to_bytes().as_slice()); assert_eq!(&key[..], search_target.to_bytes().as_slice());
assert_eq!(usize::from(step.count), 1); 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. // Set up expectations.
@ -295,7 +295,7 @@ fn query_iter() {
} }
// Ignore any other event. // Ignore any other event.
Poll::Ready(Some(_)) => (), Poll::Ready(Some(_)) => (),
e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"),
Poll::Pending => break, Poll::Pending => break,
} }
} }
@ -348,7 +348,7 @@ fn unresponsive_not_returned_direct() {
} }
// Ignore any other event. // Ignore any other event.
Poll::Ready(Some(_)) => (), Poll::Ready(Some(_)) => (),
e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"),
Poll::Pending => break, Poll::Pending => break,
} }
} }
@ -409,7 +409,7 @@ fn unresponsive_not_returned_indirect() {
} }
// Ignore any other event. // Ignore any other event.
Poll::Ready(Some(_)) => (), Poll::Ready(Some(_)) => (),
e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"),
Poll::Pending => break, Poll::Pending => break,
} }
} }
@ -466,12 +466,12 @@ fn get_record_not_found() {
assert!(closest_peers.contains(&swarm_ids[2])); assert!(closest_peers.contains(&swarm_ids[2]));
return Poll::Ready(()); return Poll::Ready(());
} else { } else {
panic!("Unexpected error result: {:?}", e); panic!("Unexpected error result: {e:?}");
} }
} }
// Ignore any other event. // Ignore any other event.
Poll::Ready(Some(_)) => (), Poll::Ready(Some(_)) => (),
e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"),
Poll::Pending => break, Poll::Pending => break,
} }
} }
@ -555,9 +555,9 @@ fn put_record() {
assert!(record.expires.is_some()); assert!(record.expires.is_some());
qids.insert(qid); 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_eq!(usize::from(index.count), 1);
assert!(index.last); assert!(index.last);
match res { match res {
Err(e) => panic!("{:?}", e), Err(e) => panic!("{e:?}"),
Ok(ok) => { Ok(ok) => {
assert!(records.contains_key(&ok.key)); assert!(records.contains_key(&ok.key));
let record = swarm.behaviour_mut().store.get(&ok.key).unwrap(); let record = swarm.behaviour_mut().store.get(&ok.key).unwrap();
@ -630,7 +630,7 @@ fn put_record() {
} }
// Ignore any other event. // Ignore any other event.
Poll::Ready(Some(_)) => (), Poll::Ready(Some(_)) => (),
e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"),
Poll::Pending => break, Poll::Pending => break,
} }
} }
@ -693,16 +693,14 @@ fn put_record() {
actual.difference(&expected).collect::<Vec<&PeerId>>(); actual.difference(&expected).collect::<Vec<&PeerId>>();
assert!( assert!(
actual_not_expected.is_empty(), actual_not_expected.is_empty(),
"Did not expect records to be stored on nodes {:?}.", "Did not expect records to be stored on nodes {actual_not_expected:?}.",
actual_not_expected,
); );
let expected_not_actual = let expected_not_actual =
expected.difference(&actual).collect::<Vec<&PeerId>>(); expected.difference(&actual).collect::<Vec<&PeerId>>();
assert!( assert!(
expected_not_actual.is_empty(), expected_not_actual.is_empty(),
"Expected record to be stored on nodes {:?}.", "Expected record to be stored on nodes {expected_not_actual:?}.",
expected_not_actual,
); );
} }
} }
@ -791,7 +789,7 @@ fn get_record() {
} }
// Ignore any other event. // Ignore any other event.
Poll::Ready(Some(_)) => (), Poll::Ready(Some(_)) => (),
e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"),
Poll::Pending => break, Poll::Pending => break,
} }
} }
@ -849,7 +847,7 @@ fn get_record_many() {
} }
// Ignore any other event. // Ignore any other event.
Poll::Ready(Some(_)) => (), Poll::Ready(Some(_)) => (),
e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"),
Poll::Pending => break, Poll::Pending => break,
} }
} }
@ -939,7 +937,7 @@ fn add_provider() {
))) => { ))) => {
assert!(qids.is_empty() || qids.remove(&id)); assert!(qids.is_empty() || qids.remove(&id));
match res { match res {
Err(e) => panic!("{:?}", e), Err(e) => panic!("{e:?}"),
Ok(ok) => { Ok(ok) => {
assert!(keys.contains(&ok.key)); assert!(keys.contains(&ok.key));
results.push(ok.key); results.push(ok.key);
@ -948,7 +946,7 @@ fn add_provider() {
} }
// Ignore any other event. // Ignore any other event.
Poll::Ready(Some(_)) => (), Poll::Ready(Some(_)) => (),
e @ Poll::Ready(_) => panic!("Unexpected return value: {:?}", e), e @ Poll::Ready(_) => panic!("Unexpected return value: {e:?}"),
Poll::Pending => break, Poll::Pending => break,
} }
} }
@ -1066,7 +1064,7 @@ fn exceed_jobs_max_queries() {
result: QueryResult::GetClosestPeers(Ok(r)), result: QueryResult::GetClosestPeers(Ok(r)),
.. ..
}) => break assert!(r.peers.is_empty()), }) => break assert!(r.peers.is_empty()),
SwarmEvent::Behaviour(e) => panic!("Unexpected event: {:?}", e), SwarmEvent::Behaviour(e) => panic!("Unexpected event: {e:?}"),
_ => {} _ => {}
} }
} else { } else {
@ -1158,7 +1156,7 @@ fn disjoint_query_does_not_finish_before_all_paths_did() {
assert_eq!(r.peer, Some(addr_trudy)); assert_eq!(r.peer, Some(addr_trudy));
} }
Ok(_) => {} Ok(_) => {}
Err(e) => panic!("{:?}", e), Err(e) => panic!("{e:?}"),
} }
} }
// Ignore any other event. // Ignore any other event.
@ -1184,7 +1182,7 @@ fn disjoint_query_does_not_finish_before_all_paths_did() {
QueryInfo::GetRecord { step, .. } => { QueryInfo::GetRecord { step, .. } => {
assert_eq!(usize::from(step.count), 2); 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 // Poll `alice` and `bob` expecting `alice` to return a successful query
@ -1368,7 +1366,7 @@ fn get_providers_single() {
result: QueryResult::StartProviding(Ok(_)), 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:?}"),
_ => {} _ => {}
} }
} }

View File

@ -362,7 +362,7 @@ impl fmt::Display for KademliaHandlerQueryErr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
KademliaHandlerQueryErr::Upgrade(err) => { KademliaHandlerQueryErr::Upgrade(err) => {
write!(f, "Error while performing Kademlia query: {}", err) write!(f, "Error while performing Kademlia query: {err}")
} }
KademliaHandlerQueryErr::UnexpectedMessage => { KademliaHandlerQueryErr::UnexpectedMessage => {
write!( write!(
@ -371,7 +371,7 @@ impl fmt::Display for KademliaHandlerQueryErr {
) )
} }
KademliaHandlerQueryErr::Io(err) => { 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}")
} }
} }
} }

View File

@ -100,7 +100,7 @@ impl<T> PeriodicJob<T> {
/// for the delay to expire. /// for the delay to expire.
fn asap(&mut self) { fn asap(&mut self) {
if let PeriodicJobState::Waiting(delay, deadline) = &mut self.state { 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; *deadline = new_deadline;
delay.reset(Duration::from_secs(1)); delay.reset(Duration::from_secs(1));
} }
@ -181,7 +181,7 @@ impl PutRecordJob {
/// The job is guaranteed to run on the next invocation of `poll`. /// The job is guaranteed to run on the next invocation of `poll`.
pub fn asap(&mut self, publish: bool) { pub fn asap(&mut self, publish: bool) {
if publish { 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() self.inner.asap()
} }

View File

@ -724,17 +724,17 @@ mod tests {
// Expire the timeout for the pending entry on the full bucket.` // Expire the timeout for the pending entry on the full bucket.`
let full_bucket = &mut table.buckets[full_bucket_index.unwrap().get()]; 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); full_bucket.pending_mut().unwrap().set_ready_at(elapsed);
match table.entry(&expected_applied.inserted.key) { match table.entry(&expected_applied.inserted.key) {
Entry::Present(_, NodeStatus::Connected) => {} Entry::Present(_, NodeStatus::Connected) => {}
x => panic!("Unexpected entry: {:?}", x), x => panic!("Unexpected entry: {x:?}"),
} }
match table.entry(&expected_applied.evicted.as_ref().unwrap().key) { match table.entry(&expected_applied.evicted.as_ref().unwrap().key) {
Entry::Absent(_) => {} Entry::Absent(_) => {}
x => panic!("Unexpected entry: {:?}", x), x => panic!("Unexpected entry: {x:?}"),
} }
assert_eq!(Some(expected_applied), table.take_applied_pending()); assert_eq!(Some(expected_applied), table.take_applied_pending());

View File

@ -548,7 +548,7 @@ mod tests {
let node = Node { key, value: () }; let node = Node { key, value: () };
match bucket.insert(node, NodeStatus::Disconnected) { match bucket.insert(node, NodeStatus::Disconnected) {
InsertResult::Full => {} InsertResult::Full => {}
x => panic!("{:?}", x), x => panic!("{x:?}"),
} }
// One-by-one fill the bucket with connected nodes, replacing the disconnected ones. // One-by-one fill the bucket with connected nodes, replacing the disconnected ones.
@ -568,20 +568,20 @@ mod tests {
InsertResult::Pending { disconnected } => { InsertResult::Pending { disconnected } => {
assert_eq!(disconnected, first_disconnected.key) assert_eq!(disconnected, first_disconnected.key)
} }
x => panic!("{:?}", x), x => panic!("{x:?}"),
} }
// Trying to insert another connected node fails. // Trying to insert another connected node fails.
match bucket.insert(node.clone(), NodeStatus::Connected) { match bucket.insert(node.clone(), NodeStatus::Connected) {
InsertResult::Full => {} InsertResult::Full => {}
x => panic!("{:?}", x), x => panic!("{x:?}"),
} }
assert!(bucket.pending().is_some()); assert!(bucket.pending().is_some());
// Apply the pending node. // Apply the pending node.
let pending = bucket.pending_mut().expect("No 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(); let result = bucket.apply_pending();
assert_eq!( assert_eq!(
result, result,
@ -603,7 +603,7 @@ mod tests {
let node = Node { key, value: () }; let node = Node { key, value: () };
match bucket.insert(node, NodeStatus::Connected) { match bucket.insert(node, NodeStatus::Connected) {
InsertResult::Full => {} InsertResult::Full => {}
x => panic!("{:?}", x), x => panic!("{x:?}"),
} }
} }

View File

@ -750,7 +750,7 @@ mod tests {
} => { } => {
assert_eq!(key.preimage(), &peer); assert_eq!(key.preimage(), &peer);
} }
Peer { state, .. } => panic!("Unexpected peer state: {:?}", state), Peer { state, .. } => panic!("Unexpected peer state: {state:?}"),
} }
let finished = iter.is_finished(); let finished = iter.is_finished();

View File

@ -933,8 +933,7 @@ mod tests {
panic!( panic!(
"Expected `ClosestDisjointPeersIter` to find all peers \ "Expected `ClosestDisjointPeersIter` to find all peers \
found by `ClosestPeersIter`, but it did not find {:?}.", found by `ClosestPeersIter`, but it did not find {closest_only:?}.",
closest_only,
); );
}; };

View File

@ -159,7 +159,7 @@ impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Failure::Timeout => f.write_str("Ping timeout"), 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"), Failure::Unsupported => write!(f, "Ping protocol not supported"),
} }
} }

View File

@ -75,7 +75,7 @@ fn ping_pong() {
result: Err(e), result: Err(e),
.. ..
})) => { })) => {
panic!("Ping failure: {:?}", e) panic!("Ping failure: {e:?}")
} }
_ => {} _ => {}
} }
@ -101,7 +101,7 @@ fn ping_pong() {
result: Err(e), result: Err(e),
.. ..
})) => { })) => {
panic!("Ping failure: {:?}", e) panic!("Ping failure: {e:?}")
} }
_ => {} _ => {}
} }

View File

@ -38,12 +38,12 @@ fn main() -> Result<(), Box<dyn Error>> {
env_logger::init(); env_logger::init();
let opt = Opt::parse(); let opt = Opt::parse();
println!("opt: {:?}", opt); println!("opt: {opt:?}");
// Create a static known PeerId based on given secret // Create a static known PeerId based on given secret
let local_key: identity::Keypair = generate_ed25519(opt.secret_key_seed); let local_key: identity::Keypair = generate_ed25519(opt.secret_key_seed);
let local_peer_id = PeerId::from(local_key.public()); 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(); let tcp_transport = tcp::async_io::Transport::default();
@ -80,10 +80,10 @@ fn main() -> Result<(), Box<dyn Error>> {
loop { loop {
match swarm.next().await.expect("Infinite Stream.") { match swarm.next().await.expect("Infinite Stream.") {
SwarmEvent::Behaviour(Event::Relay(event)) => { SwarmEvent::Behaviour(Event::Relay(event)) => {
println!("{:?}", event) println!("{event:?}")
} }
SwarmEvent::NewListenAddr { address, .. } => { SwarmEvent::NewListenAddr { address, .. } => {
println!("Listening on {:?}", address); println!("Listening on {address:?}");
} }
_ => {} _ => {}
} }

View File

@ -166,7 +166,7 @@ fn new_reservation_to_same_relay_replaces_old() {
} }
} }
SwarmEvent::Behaviour(ClientEvent::Ping(_)) => {} 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 => { SwarmEvent::ConnectionEstablished { peer_id, .. } if peer_id == dst_peer_id => {
break break
} }
e => panic!("{:?}", e), e => panic!("{e:?}"),
} }
} }
}) })
@ -434,7 +434,7 @@ async fn wait_for_reservation(
} }
} }
SwarmEvent::Behaviour(ClientEvent::Ping(_)) => {} SwarmEvent::Behaviour(ClientEvent::Ping(_)) => {}
e => panic!("{:?}", e), e => panic!("{e:?}"),
} }
} }
} }
@ -448,7 +448,7 @@ async fn wait_for_dial(client: &mut Swarm<Client>, remote: PeerId) -> bool {
return false return false
} }
SwarmEvent::Behaviour(ClientEvent::Ping(_)) => {} SwarmEvent::Behaviour(ClientEvent::Ping(_)) => {}
e => panic!("{:?}", e), e => panic!("{e:?}"),
} }
} }
} }

View File

@ -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. /// 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 { pub fn from_static(value: &'static str) -> Self {
if value.len() > 255 { if value.len() > 255 {
panic!("Namespace '{}' is too long!", value) panic!("Namespace '{value}' is too long!")
} }
Namespace(value.to_owned()) Namespace(value.to_owned())

View File

@ -116,7 +116,7 @@ impl SubstreamHandler for Stream {
Stream::PendingSend(substream, Message::DiscoverResponse(Err(error))) Stream::PendingSend(substream, Message::DiscoverResponse(Err(error)))
} }
(event, inbound) => { (event, inbound) => {
debug_assert!(false, "{:?} cannot handle event {:?}", inbound, event); debug_assert!(false, "{inbound:?} cannot handle event {event:?}");
inbound inbound
} }

View File

@ -59,7 +59,7 @@ where
fn get_rand_memory_address() -> Multiaddr { fn get_rand_memory_address() -> Multiaddr {
let address_port = rand::random::<u64>(); let address_port = rand::random::<u64>();
format!("/memory/{}", address_port) format!("/memory/{address_port}")
.parse::<Multiaddr>() .parse::<Multiaddr>()
.unwrap() .unwrap()
} }
@ -176,7 +176,7 @@ where
listener_done = true; listener_done = true;
} }
SwarmEvent::IncomingConnectionError { error, .. } => { SwarmEvent::IncomingConnectionError { error, .. } => {
panic!("Failure in incoming connection {}", error); panic!("Failure in incoming connection {error}");
} }
other => { other => {
log::debug!("Ignoring {:?}", other); log::debug!("Ignoring {:?}", other);

View File

@ -62,7 +62,7 @@ fn is_response_outbound() {
assert_eq!(&offline_peer, &peer); assert_eq!(&offline_peer, &peer);
assert_eq!(req_id, request_id1); 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); let request_id2 = swarm1.behaviour_mut().send_request(&offline_peer, ping);
@ -121,7 +121,7 @@ fn ping_protocol() {
SwarmEvent::Behaviour(Event::ResponseSent { peer, .. }) => { SwarmEvent::Behaviour(Event::ResponseSent { peer, .. }) => {
assert_eq!(&peer, &peer2_id); 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()); 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); assert_eq!(&peer, &peer2_id);
break channel; break channel;
}, },
SwarmEvent::Behaviour(ev) => panic!("Peer1: Unexpected event: {:?}", ev), SwarmEvent::Behaviour(ev) => panic!("Peer1: Unexpected event: {ev:?}"),
_ => {} _ => {}
}, },
event = swarm2.select_next_some() => { event = swarm2.select_next_some() => {
if let SwarmEvent::Behaviour(ev) = event { 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, error: InboundFailure::ConnectionClosed,
.. ..
}) => break, }) => 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 { let error = match event {
Event::OutboundFailure { error, .. } => error, 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); assert_eq!(error, OutboundFailure::ConnectionClosed);

View File

@ -725,7 +725,7 @@ fn get_meta_items(attr: &syn::Attribute) -> Option<Vec<syn::NestedMeta>> {
Ok(syn::Meta::List(ref meta)) => Some(meta.nested.iter().cloned().collect()), Ok(syn::Meta::List(ref meta)) => Some(meta.nested.iter().cloned().collect()),
Ok(_) => None, Ok(_) => None,
Err(e) => { Err(e) => {
eprintln!("error parsing attribute metadata: {}", e); eprintln!("error parsing attribute metadata: {e}");
None None
} }
} }

View File

@ -43,11 +43,11 @@ where
{ {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { 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 => { ConnectionError::KeepAliveTimeout => {
write!(f, "Connection closed due to expired keep-alive timeout.") 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 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { 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::Aborted => write!(f, "Pending connection: Aborted."),
PendingConnectionError::Transport(err) => { PendingConnectionError::Transport(err) => {
write!( write!(
f, f,
"Pending connection: Transport error on connection: {}", "Pending connection: Transport error on connection: {err}"
err
) )
} }
PendingConnectionError::ConnectionLimit(l) => { PendingConnectionError::ConnectionLimit(l) => {
write!(f, "Connection error: Connection limit: {}.", l) write!(f, "Connection error: Connection limit: {l}.")
} }
PendingConnectionError::WrongPeerId { obtained, endpoint } => { PendingConnectionError::WrongPeerId { obtained, endpoint } => {
write!( write!(
f, f,
"Pending connection: Unexpected peer ID {} at {:?}.", "Pending connection: Unexpected peer ID {obtained} at {endpoint:?}."
obtained, endpoint
) )
} }
} }

View File

@ -564,7 +564,7 @@ where
ConnectionHandlerUpgrErr::Timer => { ConnectionHandlerUpgrErr::Timer => {
write!(f, "Timer error while opening a substream") write!(f, "Timer error while opening a substream")
} }
ConnectionHandlerUpgrErr::Upgrade(err) => write!(f, "{}", err), ConnectionHandlerUpgrErr::Upgrade(err) => write!(f, "{err}"),
} }
} }
} }

View File

@ -560,7 +560,7 @@ impl DuplicateProtonameError {
impl fmt::Display for 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) { if let Ok(s) = std::str::from_utf8(&self.0) {
write!(f, "duplicate protocol name: {}", s) write!(f, "duplicate protocol name: {s}")
} else { } else {
write!(f, "duplicate protocol name: {:?}", self.0) write!(f, "duplicate protocol name: {:?}", self.0)
} }

View File

@ -1658,33 +1658,27 @@ impl From<PendingOutboundConnectionError<io::Error>> for DialError {
impl fmt::Display for DialError { impl fmt::Display for DialError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { 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::NoAddresses => write!(f, "Dial error: no addresses for peer."),
DialError::LocalPeerId => write!(f, "Dial error: tried to dial local peer id."), DialError::LocalPeerId => write!(f, "Dial error: tried to dial local peer id."),
DialError::Banned => write!(f, "Dial error: peer is banned."), DialError::Banned => write!(f, "Dial error: peer is banned."),
DialError::DialPeerConditionFalse(c) => { DialError::DialPeerConditionFalse(c) => {
write!( write!(f, "Dial error: condition {c:?} for dialing peer was false.")
f,
"Dial error: condition {:?} for dialing peer was false.",
c
)
} }
DialError::Aborted => write!( DialError::Aborted => write!(
f, f,
"Dial error: Pending connection attempt has been aborted." "Dial error: Pending connection attempt has been aborted."
), ),
DialError::InvalidPeerId(multihash) => { 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!( DialError::WrongPeerId { obtained, endpoint } => write!(
f, f,
"Dial error: Unexpected peer ID {} at {:?}.", "Dial error: Unexpected peer ID {obtained} at {endpoint:?}."
obtained, endpoint
), ),
DialError::ConnectionIo(e) => write!( DialError::ConnectionIo(e) => write!(
f, f,
"Dial error: An I/O error occurred on the connection: {:?}.", "Dial error: An I/O error occurred on the connection: {e:?}."
e
), ),
DialError::Transport(errors) => { DialError::Transport(errors) => {
write!(f, "Failed to negotiate transport protocol(s): [")?; write!(f, "Failed to negotiate transport protocol(s): [")?;
@ -2263,7 +2257,7 @@ mod tests {
panic!("Unexpected transport event.") panic!("Unexpected transport event.")
} }
Either::Right((e, _)) => { 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() { match swarm.next().await.unwrap() {
SwarmEvent::OutgoingConnectionError { .. } => {} 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.current, outgoing_limit);
assert_eq!(limit.limit, outgoing_limit); assert_eq!(limit.limit, outgoing_limit);
} }
e => panic!("Unexpected error: {:?}", e), e => panic!("Unexpected error: {e:?}"),
} }
let info = network.network_info(); let info = network.network_info();
@ -2351,7 +2345,7 @@ mod tests {
let listen_addr = async_std::task::block_on(poll_fn(|cx| { let listen_addr = async_std::task::block_on(poll_fn(|cx| {
match ready!(network1.poll_next_unpin(cx)).unwrap() { match ready!(network1.poll_next_unpin(cx)).unwrap() {
SwarmEvent::NewListenAddr { address, .. } => Poll::Ready(address), 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 => { Poll::Pending => {
network_1_pending = true; network_1_pending = true;
} }
e => panic!("Unexpected network event: {:?}", e), e => panic!("Unexpected network event: {e:?}"),
} }
match network2.poll_next_unpin(cx) { match network2.poll_next_unpin(cx) {
@ -2408,7 +2402,7 @@ mod tests {
Poll::Pending => { Poll::Pending => {
network_2_pending = true; network_2_pending = true;
} }
e => panic!("Unexpected network event: {:?}", e), e => panic!("Unexpected network event: {e:?}"),
} }
if network_1_pending && network_2_pending { if network_1_pending && network_2_pending {
@ -2478,7 +2472,7 @@ mod tests {
Poll::Ready(Some(SwarmEvent::OutgoingConnectionError { Poll::Ready(Some(SwarmEvent::OutgoingConnectionError {
peer_id, error, .. peer_id, error, ..
})) => Poll::Ready((peer_id, error)), })) => Poll::Ready((peer_id, error)),
Poll::Ready(x) => panic!("unexpected {:?}", x), Poll::Ready(x) => panic!("unexpected {x:?}"),
Poll::Pending => Poll::Pending, 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); assert_eq!(local_addr, local_address);
} }
Poll::Ready(ev) => { Poll::Ready(ev) => {
panic!("Unexpected event: {:?}", ev) panic!("Unexpected event: {ev:?}")
} }
Poll::Pending => break Poll::Pending, Poll::Pending => break Poll::Pending,
} }
@ -2631,7 +2625,7 @@ mod tests {
listener.listen_on(multiaddr![Memory(0u64)]).unwrap(); listener.listen_on(multiaddr![Memory(0u64)]).unwrap();
let listener_address = match block_on(listener.next()).unwrap() { let listener_address = match block_on(listener.next()).unwrap() {
SwarmEvent::NewListenAddr { address, .. } => address, SwarmEvent::NewListenAddr { address, .. } => address,
e => panic!("Unexpected network event: {:?}", e), e => panic!("Unexpected network event: {e:?}"),
}; };
dialer dialer
@ -2651,7 +2645,7 @@ mod tests {
error: DialError::Aborted, error: DialError::Aborted,
.. ..
} => {} } => {}
e => panic!("Unexpected swarm event {:?}.", e), e => panic!("Unexpected swarm event {e:?}."),
} }
} }

View File

@ -410,9 +410,9 @@ where
{ {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
DnsErr::Transport(err) => write!(f, "{}", err), DnsErr::Transport(err) => write!(f, "{err}"),
DnsErr::ResolveError(err) => write!(f, "{}", err), DnsErr::ResolveError(err) => write!(f, "{err}"),
DnsErr::MultiaddrNotSupported(a) => write!(f, "Unsupported resolved address: {}", a), DnsErr::MultiaddrNotSupported(a) => write!(f, "Unsupported resolved address: {a}"),
DnsErr::TooManyLookups => write!(f, "Too many DNS lookups"), DnsErr::TooManyLookups => write!(f, "Too many DNS lookups"),
} }
} }
@ -692,7 +692,7 @@ mod tests {
.await .await
{ {
Err(DnsErr::ResolveError(_)) => {} Err(DnsErr::ResolveError(_)) => {}
Err(e) => panic!("Unexpected error: {:?}", e), Err(e) => panic!("Unexpected error: {e:?}"),
Ok(_) => panic!("Unexpected success."), Ok(_) => panic!("Unexpected success."),
} }
@ -704,9 +704,9 @@ mod tests {
{ {
Err(DnsErr::ResolveError(e)) => match e.kind() { Err(DnsErr::ResolveError(e)) => match e.kind() {
ResolveErrorKind::NoRecordsFound { .. } => {} 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."), Ok(_) => panic!("Unexpected success."),
} }
} }

View File

@ -294,7 +294,7 @@ fn run<I, C>(
match server_session.read_exact(&mut n).await { match server_session.read_exact(&mut n).await {
Ok(()) => u64::from_be_bytes(n), Ok(()) => u64::from_be_bytes(n),
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => 0, 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); info!("server: reading message ({} bytes)", len);

View File

@ -70,7 +70,7 @@ impl error::Error for PlainTextError {
impl fmt::Display for PlainTextError { impl fmt::Display for PlainTextError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self { 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::InvalidPayload(_) => f.write_str("Failed to decode protobuf"),
PlainTextError::PeerIdMismatch => f.write_str( PlainTextError::PeerIdMismatch => f.write_str(
"The peer id of the exchange isn't consistent with the remote public key", "The peer id of the exchange isn't consistent with the remote public key",

View File

@ -102,7 +102,7 @@ fn to_hex(bytes: &[u8]) -> String {
let mut hex = String::with_capacity(bytes.len() * 2); let mut hex = String::with_capacity(bytes.len() * 2);
for byte in bytes { 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 hex
@ -174,7 +174,7 @@ pub enum KeyParseError {
impl fmt::Display for KeyParseError { impl fmt::Display for KeyParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 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] #[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self { match self {
PnetError::HandshakeError(e) => write!(f, "Handshake error: {}", e), PnetError::HandshakeError(e) => write!(f, "Handshake error: {e}"),
PnetError::IoError(e) => write!(f, "I/O error: {}", e), PnetError::IoError(e) => write!(f, "I/O error: {e}"),
} }
} }
} }

View File

@ -236,8 +236,7 @@ impl StreamMuxer for Connection {
quinn_proto::Event::Connected | quinn_proto::Event::HandshakeDataReady => { quinn_proto::Event::Connected | quinn_proto::Event::HandshakeDataReady => {
debug_assert!( debug_assert!(
false, false,
"Unexpected event {:?} on established QUIC connection", "Unexpected event {event:?} on established QUIC connection"
event
); );
} }
quinn_proto::Event::ConnectionLost { reason } => { quinn_proto::Event::ConnectionLost { reason } => {

View File

@ -520,7 +520,7 @@ impl<P: Provider> Driver<P> {
// `event` has type `quinn_proto::ConnectionEvent`, which has multiple // `event` has type `quinn_proto::ConnectionEvent`, which has multiple
// variants. `quinn_proto::Endpoint::handle` however only ever returns // variants. `quinn_proto::Endpoint::handle` however only ever returns
// `ConnectionEvent::Datagram`. // `ConnectionEvent::Datagram`.
debug_assert!(format!("{:?}", event).contains("Datagram")); debug_assert!(format!("{event:?}").contains("Datagram"));
// Redirect the datagram to its connection. // Redirect the datagram to its connection.
if let Some(sender) = self.alive_connections.get_mut(&connec_id) { if let Some(sender) = self.alive_connections.get_mut(&connec_id) {

View File

@ -771,7 +771,7 @@ mod test {
); );
assert!(matches!(listen_addr.iter().nth(2), Some(Protocol::QuicV1))); 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."); assert!(transport.remove_listener(id), "Expect listener to exist.");
match poll_fn(|cx| Pin::new(&mut transport).as_mut().poll(cx)).await { match poll_fn(|cx| Pin::new(&mut transport).as_mut().poll(cx)).await {
@ -781,7 +781,7 @@ mod test {
} => { } => {
assert_eq!(listener_id, id); 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 // Poll once again so that the listener has the chance to return `Poll::Ready(None)` and
// be removed from the list of listeners. // be removed from the list of listeners.

View File

@ -405,7 +405,7 @@ async fn start_listening(transport: &mut Boxed<(PeerId, StreamMuxerBox)>, addr:
transport.listen_on(addr.parse().unwrap()).unwrap(); transport.listen_on(addr.parse().unwrap()).unwrap();
match transport.next().await { match transport.next().await {
Some(TransportEvent::NewAddress { listen_addr, .. }) => listen_addr, Some(TransportEvent::NewAddress { listen_addr, .. }) => listen_addr,
e => panic!("{:?}", e), e => panic!("{e:?}"),
} }
} }

View File

@ -952,7 +952,7 @@ mod tests {
upgrade.write_all(&[4, 5, 6]).await.unwrap(); upgrade.write_all(&[4, 5, 6]).await.unwrap();
return; 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") { match iter.next().expect("ip address") {
Protocol::Ip4(ip) => assert!(!ip.is_unspecified()), Protocol::Ip4(ip) => assert!(!ip.is_unspecified()),
Protocol::Ip6(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") { if let Protocol::Tcp(port) = iter.next().expect("port") {
assert_ne!(0, port) assert_ne!(0, port)
} else { } else {
panic!("No TCP port in address: {}", listen_addr) panic!("No TCP port in address: {listen_addr}")
} }
ready_tx.send(listen_addr).await.ok(); ready_tx.send(listen_addr).await.ok();
} }
@ -1103,7 +1103,7 @@ mod tests {
upgrade.write_all(&[4, 5, 6]).await.unwrap(); upgrade.write_all(&[4, 5, 6]).await.unwrap();
return; return;
} }
e => panic!("Unexpected event: {:?}", e), e => panic!("Unexpected event: {e:?}"),
} }
} }
} }
@ -1140,7 +1140,7 @@ mod tests {
socket.read_exact(&mut buf).await.unwrap(); socket.read_exact(&mut buf).await.unwrap();
assert_eq!(buf, [4, 5, 6]); 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 { TransportEvent::NewAddress {
listen_addr: addr2, .. listen_addr: addr2, ..
} => assert_eq!(addr1, 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:?}"),
} }
} }

View File

@ -519,7 +519,7 @@ mod tests {
let error = parse(&certificate).unwrap_err(); let error = parse(&certificate).unwrap_err();
assert_eq!(format!("{}", error), "UnknownIssuer"); assert_eq!(format!("{error}"), "UnknownIssuer");
} }
#[test] #[test]

View File

@ -238,7 +238,7 @@ impl From<certificate::ParseError> for rustls::Error {
use webpki::Error::*; use webpki::Error::*;
match e { match e {
BadDer => rustls::Error::InvalidCertificateEncoding, 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<certificate::VerificationError> for rustls::Error {
UnsupportedSignatureAlgorithm | UnsupportedSignatureAlgorithmForPublicKey => { UnsupportedSignatureAlgorithm | UnsupportedSignatureAlgorithmForPublicKey => {
rustls::Error::InvalidCertificateSignatureType rustls::Error::InvalidCertificateSignatureType
} }
e => rustls::Error::InvalidCertificateData(format!("invalid peer certificate: {}", e)), e => rustls::Error::InvalidCertificateData(format!("invalid peer certificate: {e}")),
} }
} }
} }

View File

@ -30,7 +30,7 @@ async fn can_establish_connection() {
match swarm1.next().await.unwrap() { match swarm1.next().await.unwrap() {
SwarmEvent::ConnectionEstablished { peer_id, .. } => break peer_id, SwarmEvent::ConnectionEstablished { peer_id, .. } => break peer_id,
SwarmEvent::IncomingConnectionError { error, .. } => { SwarmEvent::IncomingConnectionError { error, .. } => {
panic!("Incoming connection failed: {}", error) panic!("Incoming connection failed: {error}")
} }
_ => continue, _ => continue,
}; };
@ -41,7 +41,7 @@ async fn can_establish_connection() {
match swarm2.next().await.unwrap() { match swarm2.next().await.unwrap() {
SwarmEvent::ConnectionEstablished { peer_id, .. } => break peer_id, SwarmEvent::ConnectionEstablished { peer_id, .. } => break peer_id,
SwarmEvent::OutgoingConnectionError { error, .. } => { SwarmEvent::OutgoingConnectionError { error, .. } => {
panic!("Failed to dial: {}", error) panic!("Failed to dial: {error}")
} }
_ => continue, _ => continue,
}; };

View File

@ -631,14 +631,14 @@ impl From<JsErr> for io::Error {
impl fmt::Debug for JsErr { impl fmt::Debug for JsErr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self) write!(f, "{self}")
} }
} }
impl fmt::Display for JsErr { impl fmt::Display for JsErr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(s) = self.0.as_string() { if let Some(s) = self.0.as_string() {
write!(f, "{}", s) write!(f, "{s}")
} else if let Some(err) = self.0.dyn_ref::<js_sys::Error>() { } else if let Some(err) = self.0.dyn_ref::<js_sys::Error>() {
write!(f, "{}", String::from(err.message())) write!(f, "{}", String::from(err.message()))
} else if let Some(obj) = self.0.dyn_ref::<js_sys::Object>() { } else if let Some(obj) = self.0.dyn_ref::<js_sys::Object>() {

View File

@ -83,7 +83,7 @@ impl Fingerprint {
/// ///
/// This is the format described in <https://www.rfc-editor.org/rfc/rfc4572#section-5>. /// This is the format described in <https://www.rfc-editor.org/rfc/rfc4572#section-5>.
pub fn to_sdp_format(self) -> String { 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"). /// Returns the algorithm used (e.g. "sha-256").

View File

@ -598,7 +598,7 @@ mod tests {
); );
assert!(matches!(listen_addr.iter().nth(2), Some(Protocol::WebRTC))); assert!(matches!(listen_addr.iter().nth(2), Some(Protocol::WebRTC)));
} }
e => panic!("Unexpected event: {:?}", e), e => panic!("Unexpected event: {e:?}"),
} }
assert!( assert!(
transport.remove_listener(listener), transport.remove_listener(listener),
@ -611,7 +611,7 @@ mod tests {
} => { } => {
assert_eq!(listener_id, listener); 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 // Poll once again so that the listener has the chance to return `Poll::Ready(None)` and
// be removed from the list of listeners. // be removed from the list of listeners.

View File

@ -537,10 +537,7 @@ fn ufrag_from_stun_message(buffer: &[u8], local_ufrag: bool) -> Result<String, E
}; };
if let Err(err) = result { if let Err(err) = result {
Err(Error::Other(format!( Err(Error::Other(format!("failed to handle decode ICE: {err}")))
"failed to handle decode ICE: {}",
err
)))
} else { } else {
let (attr, found) = message.attributes.get(ATTR_USERNAME); let (attr, found) = message.attributes.get(ATTR_USERNAME);
if !found { if !found {
@ -551,8 +548,7 @@ fn ufrag_from_stun_message(buffer: &[u8], local_ufrag: bool) -> Result<String, E
// Per the RFC this shouldn't happen // Per the RFC this shouldn't happen
// https://datatracker.ietf.org/doc/html/rfc5389#section-15.3 // https://datatracker.ietf.org/doc/html/rfc5389#section-15.3
Err(err) => Err(Error::Other(format!( Err(err) => Err(Error::Other(format!(
"failed to decode USERNAME from STUN message as UTF-8: {}", "failed to decode USERNAME from STUN message as UTF-8: {err}"
err
))), ))),
Ok(s) => { Ok(s) => {
// s is a combination of the local_ufrag and the remote ufrag separated by `:`. // s is a combination of the local_ufrag and the remote ufrag separated by `:`.

View File

@ -83,7 +83,7 @@ async fn start_listening(transport: &mut Boxed<(PeerId, StreamMuxerBox)>, addr:
transport.listen_on(addr.parse().unwrap()).unwrap(); transport.listen_on(addr.parse().unwrap()).unwrap();
match transport.next().await { match transport.next().await {
Some(TransportEvent::NewAddress { listen_addr, .. }) => listen_addr, Some(TransportEvent::NewAddress { listen_addr, .. }) => listen_addr,
e => panic!("{:?}", e), e => panic!("{e:?}"),
} }
} }

View File

@ -44,13 +44,13 @@ pub enum Error<E> {
impl<E: fmt::Display> fmt::Display for Error<E> { impl<E: fmt::Display> fmt::Display for Error<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Error::Transport(err) => write!(f, "{}", err), Error::Transport(err) => write!(f, "{err}"),
Error::Tls(err) => write!(f, "{}", err), Error::Tls(err) => write!(f, "{err}"),
Error::Handshake(err) => write!(f, "{}", err), Error::Handshake(err) => write!(f, "{err}"),
Error::InvalidMultiaddr(ma) => write!(f, "invalid multi-address: {}", ma), Error::InvalidMultiaddr(ma) => write!(f, "invalid multi-address: {ma}"),
Error::TooManyRedirects => f.write_str("too many redirects"), Error::TooManyRedirects => f.write_str("too many redirects"),
Error::InvalidRedirectLocation => f.write_str("invalid redirect location"), Error::InvalidRedirectLocation => f.write_str("invalid redirect location"),
Error::Base(err) => write!(f, "{}", err), Error::Base(err) => write!(f, "{err}"),
} }
} }
} }

View File

@ -381,7 +381,7 @@ where
Ok(Either::Left(location)) Ok(Either::Left(location))
} }
handshake::ServerResponse::Rejected { status_code } => { 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())) Err(Error::Handshake(msg.into()))
} }
handshake::ServerResponse::Accepted { .. } => { handshake::ServerResponse::Accepted { .. } => {
@ -501,10 +501,10 @@ fn parse_ws_dial_addr<T>(addr: Multiaddr) -> Result<WsAddress, Error<T>> {
let (host_port, dns_name) = loop { let (host_port, dns_name) = loop {
match (ip, tcp) { match (ip, tcp) {
(Some(Protocol::Ip4(ip)), Some(Protocol::Tcp(port))) => { (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))) => { (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::Dns(h)), Some(Protocol::Tcp(port)))
| (Some(Protocol::Dns4(h)), Some(Protocol::Tcp(port))) | (Some(Protocol::Dns4(h)), Some(Protocol::Tcp(port)))

View File

@ -167,9 +167,9 @@ pub enum Error {
impl fmt::Display for 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 { match self {
Error::Io(e) => write!(f, "i/o error: {}", e), Error::Io(e) => write!(f, "i/o error: {e}"),
Error::Tls(e) => write!(f, "tls error: {}", e), Error::Tls(e) => write!(f, "tls error: {e}"),
Error::InvalidDnsName(n) => write!(f, "invalid DNS name: {}", n), Error::InvalidDnsName(n) => write!(f, "invalid DNS name: {n}"),
} }
} }
} }