Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: activate clippy::manual_let_else lint #4770

Merged
merged 21 commits into from
Nov 14, 2023
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ clippy.used_underscore_binding = "warn"
clippy.pedantic = "allow"
clippy.type_complexity = "allow"
clippy.unnecessary_wraps = "warn"
clippy.manual_let_else = "warn"
clippy.dbg_macro = "warn"

[workspace.metadata.release]
Expand Down
12 changes: 6 additions & 6 deletions core/src/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,16 +401,16 @@ impl<TUpgr, TErr> TransportEvent<TUpgr, TErr> {
/// Returns `None` if the event is not actually an incoming connection,
/// otherwise the upgrade and the remote address.
pub fn into_incoming(self) -> Option<(TUpgr, Multiaddr)> {
if let TransportEvent::Incoming {
let TransportEvent::Incoming {
upgrade,
send_back_addr,
..
} = self
{
Some((upgrade, send_back_addr))
} else {
None
}
else {
return None;
};

Some((upgrade, send_back_addr))
}

/// Returns `true` if this is a [`TransportEvent::NewAddress`].
Expand Down
19 changes: 7 additions & 12 deletions core/src/transport/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,8 @@ impl Hub {
port
} else {
loop {
let port = match NonZeroU64::new(rand::random()) {
Some(p) => p,
None => continue,
let Some(port) = NonZeroU64::new(rand::random()) else {
continue;
};
if !hub.contains_key(&port) {
break port;
Expand Down Expand Up @@ -184,16 +183,12 @@ impl Transport for MemoryTransport {
id: ListenerId,
addr: Multiaddr,
) -> Result<(), TransportError<Self::Error>> {
let port = if let Ok(port) = parse_memory_addr(&addr) {
port
} else {
return Err(TransportError::MultiaddrNotSupported(addr));
};
let port =
parse_memory_addr(&addr).map_err(|_| TransportError::MultiaddrNotSupported(addr))?;

let (rx, port) = match HUB.register_port(port) {
Some((rx, port)) => (rx, port),
None => return Err(TransportError::Other(MemoryTransportError::Unreachable)),
};
let (rx, port) = HUB
.register_port(port)
.ok_or(TransportError::Other(MemoryTransportError::Unreachable))?;

let listener = Listener {
id,
Expand Down
5 changes: 2 additions & 3 deletions examples/browser-webrtc/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,8 @@ struct StaticFiles;

/// Serve the Multiaddr we are listening on and the host files.
pub(crate) async fn serve(libp2p_transport: Multiaddr) {
let listen_addr = match libp2p_transport.iter().next() {
Some(Protocol::Ip4(addr)) => addr,
_ => panic!("Expected 1st protocol to be IP4"),
let Some(Protocol::Ip4(listen_addr)) = libp2p_transport.iter().next() else {
panic!("Expected 1st protocol to be IP4")
};

let server = Router::new()
Expand Down
5 changes: 2 additions & 3 deletions examples/file-sharing/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,8 @@ async fn main() -> Result<(), Box<dyn Error>> {

// In case the user provided an address of a peer on the CLI, dial it.
if let Some(addr) = opt.peer {
let peer_id = match addr.iter().last() {
Some(Protocol::P2p(peer_id)) => peer_id,
_ => return Err("Expect peer multiaddr to contain peer ID.".into()),
let Some(Protocol::P2p(peer_id)) = addr.iter().last() else {
return Err("Expect peer multiaddr to contain peer ID.".into());
};
network_client
.dial(peer_id, addr)
Expand Down
9 changes: 3 additions & 6 deletions misc/memory-connection-limits/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,12 +124,9 @@ impl Behaviour {
return;
}

let stats = match memory_stats::memory_stats() {
Some(stats) => stats,
None => {
tracing::warn!("Failed to retrieve process memory stats");
return;
}
let Some(stats) = memory_stats::memory_stats() else {
tracing::warn!("Failed to retrieve process memory stats");
return;
};

self.last_refreshed = now;
Expand Down
8 changes: 2 additions & 6 deletions muxers/mplex/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -912,9 +912,7 @@ where
/// Fails the entire multiplexed stream if too many pending `Reset`
/// frames accumulate when using [`MaxBufferBehaviour::ResetStream`].
fn buffer(&mut self, id: LocalStreamId, data: Bytes) -> io::Result<()> {
let state = if let Some(state) = self.substreams.get_mut(&id) {
state
} else {
let Some(state) = self.substreams.get_mut(&id) else {
tracing::trace!(
connection=%self.id,
substream=%id,
Expand All @@ -924,9 +922,7 @@ where
return Ok(());
};

let buf = if let Some(buf) = state.recv_buf_open() {
buf
} else {
let Some(buf) = state.recv_buf_open() else {
tracing::trace!(
connection=%self.id,
substream=%id,
Expand Down
17 changes: 5 additions & 12 deletions protocols/autonat/src/behaviour/as_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,13 +278,9 @@ impl<'a> AsClient<'a> {
tracing::debug!("Outbound dial-back request aborted: No dial-back addresses");
return Err(OutboundProbeError::NoAddresses);
}
let server = match self.random_server() {
Some(s) => s,
None => {
tracing::debug!("Outbound dial-back request aborted: No qualified server");
return Err(OutboundProbeError::NoServer);
}
};

let server = self.random_server().ok_or(OutboundProbeError::NoServer)?;

let request_id = self.inner.send_request(
&server,
DialRequest {
Expand All @@ -301,11 +297,8 @@ impl<'a> AsClient<'a> {
// Set the delay to the next probe based on the time of our last probe
// and the specified delay.
fn schedule_next_probe(&mut self, delay: Duration) {
let last_probe_instant = match self.last_probe {
Some(instant) => instant,
None => {
return;
}
let Some(last_probe_instant) = self.last_probe else {
return;
};
let schedule_next = *last_probe_instant + delay;
self.schedule_probe
Expand Down
8 changes: 4 additions & 4 deletions protocols/autonat/src/behaviour/as_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,13 +326,13 @@ impl<'a> AsServer<'a> {
demanded: Vec<Multiaddr>,
observed_remote_at: &Multiaddr,
) -> Vec<Multiaddr> {
let observed_ip = match observed_remote_at
let Some(observed_ip) = observed_remote_at
.into_iter()
.find(|p| matches!(p, Protocol::Ip4(_) | Protocol::Ip6(_)))
{
Some(ip) => ip,
None => return Vec::new(),
else {
return Vec::new();
};

let mut distinct = HashSet::new();
demanded
.into_iter()
Expand Down
28 changes: 12 additions & 16 deletions protocols/autonat/src/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,22 +119,18 @@ impl DialRequest {
if msg.type_pb != Some(proto::MessageType::DIAL) {
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid type"));
}
let (peer_id, addrs) = if let Some(proto::Dial {
peer:
Some(proto::PeerInfo {
id: Some(peer_id),
addrs,
}),
}) = msg.dial
{
(peer_id, addrs)
} else {
tracing::debug!("Received malformed dial message");
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"invalid dial message",
));
};

let peer_id_result = msg.dial.and_then(|dial| {
dial.peer.and_then(|peer_info| {
let Some(peer_id) = peer_info.id else {
return None;
};
Some((peer_id, peer_info.addrs))
})
});

let (peer_id, addrs) = peer_id_result
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "invalid dial message"))?;

let peer_id = {
PeerId::try_from(peer_id.to_vec())
Expand Down
60 changes: 28 additions & 32 deletions protocols/dcutr/src/behaviour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,33 +104,27 @@ impl Behaviour {
..
}: DialFailure,
) {
let peer_id = if let Some(peer_id) = peer_id {
peer_id
} else {
let Some(peer_id) = peer_id else {
eserilev marked this conversation as resolved.
Show resolved Hide resolved
return;
};

let relayed_connection_id = if let Some(relayed_connection_id) = self
let Some(relayed_connection_id) = self
.direct_to_relayed_connections
.get(&failed_direct_connection)
{
*relayed_connection_id
} else {
else {
return;
};

let attempt = if let Some(attempt) = self
let Some(attempt) = self
.outgoing_direct_connection_attempts
.get(&(relayed_connection_id, peer_id))
{
*attempt
} else {
.get(&(*relayed_connection_id, peer_id))
else {
return;
};

if attempt < MAX_NUMBER_OF_UPGRADE_ATTEMPTS {
if *attempt < MAX_NUMBER_OF_UPGRADE_ATTEMPTS {
self.queued_events.push_back(ToSwarm::NotifyHandler {
handler: NotifyHandler::One(relayed_connection_id),
handler: NotifyHandler::One(*relayed_connection_id),
peer_id,
event: Either::Left(handler::relayed::Command::Connect),
})
Expand Down Expand Up @@ -229,23 +223,25 @@ impl NetworkBehaviour for Behaviour {
.insert(connection_id);

// Whether this is a connection requested by this behaviour.
if let Some(&relayed_connection_id) = self.direct_to_relayed_connections.get(&connection_id)
{
if role_override == Endpoint::Listener {
assert!(
self.outgoing_direct_connection_attempts
.remove(&(relayed_connection_id, peer))
.is_some(),
"state mismatch"
);
}
let Some(&relayed_connection_id) = self.direct_to_relayed_connections.get(&connection_id)
else {
panic!("no direct connection for this connection id")
eserilev marked this conversation as resolved.
Show resolved Hide resolved
};

self.queued_events.extend([ToSwarm::GenerateEvent(Event {
remote_peer_id: peer,
result: Ok(connection_id),
})]);
if role_override == Endpoint::Listener {
assert!(
self.outgoing_direct_connection_attempts
.remove(&(relayed_connection_id, peer))
.is_some(),
"state mismatch"
);
}

self.queued_events.extend([ToSwarm::GenerateEvent(Event {
remote_peer_id: peer,
result: Ok(connection_id),
})]);

Ok(Either::Right(dummy::ConnectionHandler))
}

Expand Down Expand Up @@ -323,11 +319,11 @@ impl NetworkBehaviour for Behaviour {
}

fn poll(&mut self, _: &mut Context<'_>) -> Poll<ToSwarm<Self::ToSwarm, THandlerInEvent<Self>>> {
if let Some(event) = self.queued_events.pop_front() {
return Poll::Ready(event);
}
let Some(event) = self.queued_events.pop_front() else {
return Poll::Pending;
};

Poll::Pending
eserilev marked this conversation as resolved.
Show resolved Hide resolved
return Poll::Ready(event);
}

fn on_swarm_event(&mut self, event: FromSwarm) {
Expand Down
5 changes: 2 additions & 3 deletions protocols/floodsub/src/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,8 @@ impl Floodsub {
///
/// Returns true if we were subscribed to this topic.
pub fn unsubscribe(&mut self, topic: Topic) -> bool {
let pos = match self.subscribed_topics.iter().position(|t| *t == topic) {
Some(pos) => pos,
None => return false,
let Some(pos) = self.subscribed_topics.iter().position(|t| *t == topic) else {
return false;
};

self.subscribed_topics.remove(pos);
Expand Down
30 changes: 12 additions & 18 deletions protocols/gossipsub/src/behaviour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1895,15 +1895,12 @@ where

let mut unsubscribed_peers = Vec::new();

let subscribed_topics = match self.peer_topics.get_mut(propagation_source) {
Some(topics) => topics,
None => {
tracing::error!(
peer=%propagation_source,
"Subscription by unknown peer"
);
return;
}
let Some(subscribed_topics) = self.peer_topics.get_mut(propagation_source) else {
tracing::error!(
peer=%propagation_source,
"Subscription by unknown peer"
);
return;
};

// Collect potential graft topics for the peer.
Expand Down Expand Up @@ -3152,15 +3149,12 @@ where
// remove from mesh, topic_peers, peer_topic and the fanout
tracing::debug!(peer=%peer_id, "Peer disconnected");
{
let topics = match self.peer_topics.get(&peer_id) {
Some(topics) => topics,
None => {
debug_assert!(
self.blacklisted_peers.contains(&peer_id),
"Disconnected node not in connected list"
);
return;
}
let Some(topics) = self.peer_topics.get(&peer_id) else {
debug_assert!(
self.blacklisted_peers.contains(&peer_id),
"Disconnected node not in connected list"
);
return;
};

// remove peer from all mappings
Expand Down
6 changes: 2 additions & 4 deletions protocols/gossipsub/src/peer_score.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,11 +220,9 @@ impl PeerScore {
/// Returns the score for a peer, logging metrics. This is called from the heartbeat and
/// increments the metric counts for penalties.
pub(crate) fn metric_score(&self, peer_id: &PeerId, mut metrics: Option<&mut Metrics>) -> f64 {
let peer_stats = match self.peer_stats.get(peer_id) {
Some(v) => v,
None => return 0.0,
let Some(peer_stats) = self.peer_stats.get(peer_id) else {
return 0.0;
};

let mut score = 0.0;

// topic scores
Expand Down
Loading
Loading