Skip to content

Commit

Permalink
Fix many clippy warnings (#1849)
Browse files Browse the repository at this point in the history
* Fix many clippy warnings

* Fix unused imports
  • Loading branch information
tomaka authored May 29, 2024
1 parent 41b33b7 commit 69449dc
Show file tree
Hide file tree
Showing 12 changed files with 82 additions and 105 deletions.
22 changes: 10 additions & 12 deletions lib/src/executor/vm/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,18 +49,16 @@ fn basic_seems_to_work() {
)
.unwrap();

loop {
match vm.run(None) {
Ok(super::ExecOutcome::Finished {
return_value: Ok(_),
}) => break,
Ok(super::ExecOutcome::Finished {
return_value: Err(_),
}) => panic!(),
Ok(super::ExecOutcome::Interrupted { id: 0, .. }) => break,
Ok(super::ExecOutcome::Interrupted { .. }) => panic!(),
Err(_) => panic!(),
}
match vm.run(None) {
Ok(super::ExecOutcome::Finished {
return_value: Ok(_),
}) => {}
Ok(super::ExecOutcome::Finished {
return_value: Err(_),
}) => panic!(),
Ok(super::ExecOutcome::Interrupted { id: 0, .. }) => {}
Ok(super::ExecOutcome::Interrupted { .. }) => panic!(),
Err(_) => panic!(),
}
}
}
Expand Down
3 changes: 1 addition & 2 deletions lib/src/libp2p/collection/single_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -745,8 +745,7 @@ where
self.connection = SingleStreamConnectionTaskInner::Established {
established: connection,
outbound_substreams_map,
notifications_in_close_acknowledgments:
notifications_in_close_acknowledgments,
notifications_in_close_acknowledgments,
inbound_negotiated_cancel_acknowledgments,
};
}
Expand Down
1 change: 0 additions & 1 deletion lib/src/libp2p/connection/yamux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2050,7 +2050,6 @@ where
// Because the number of queuable bytes is capped by the value in
// `Config::max_out_data_frame_size`, we are guaranteed that the length
// to write out fits in a `u32`.
debug_assert!(self.yamux.inner.max_out_data_frame_size.get() <= u32::MAX);
u32::try_from(self.inner_read_write.write_bytes_queued).unwrap()
},
},
Expand Down
12 changes: 6 additions & 6 deletions lib/src/libp2p/multihash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ pub struct Multihash<T = Vec<u8>>(T);
impl<T: AsRef<[u8]>> Multihash<T> {
/// Returns the code stored in this multihash.
pub fn hash_algorithm_code(&self) -> u32 {
decode(&self.0.as_ref()).unwrap().0
decode(self.0.as_ref()).unwrap().0
}

/// Returns the data stored in this multihash.
pub fn data(&self) -> &[u8] {
decode(&self.0.as_ref()).unwrap().1
decode(self.0.as_ref()).unwrap().1
}

/// Checks whether `input` is a valid multihash.
Expand All @@ -61,7 +61,7 @@ impl<T: AsRef<[u8]>> Multihash<T> {
impl<'a> Multihash<&'a [u8]> {
/// Returns the data stored in this multihash.
pub fn data_ref(&self) -> &'a [u8] {
decode(&self.0.as_ref()).unwrap().1
decode(self.0).unwrap().1
}

/// Checks whether `input` is a valid multihash.
Expand All @@ -72,7 +72,7 @@ impl<'a> Multihash<&'a [u8]> {
input: &'a [u8],
) -> Result<(Multihash<&'a [u8]>, &'a [u8]), FromBytesError> {
match multihash::<nom::error::Error<&[u8]>>(input) {
Ok((rest, _)) => Ok((Multihash(&input.as_ref()[..rest.len()]), rest)),
Ok((rest, _)) => Ok((Multihash(&input[..rest.len()]), rest)),
Err(_) => Err(FromBytesError::DecodeError),
}
}
Expand All @@ -83,7 +83,7 @@ impl Multihash<Vec<u8>> {
///
/// Calling [`Multihash::data`] on the returned value will always yield back the same data
/// as was passed as parameter.
pub fn identity<'a>(data: &'a [u8]) -> Self {
pub fn identity(data: &[u8]) -> Self {
let mut out = Vec::with_capacity(data.len() + 8);
out.extend(util::leb128::encode(0u32));
out.extend(util::leb128::encode_usize(data.len()));
Expand Down Expand Up @@ -118,7 +118,7 @@ impl<T: AsRef<[u8]>> fmt::Display for Multihash<T> {
}
}

fn decode<'a>(bytes: &'a [u8]) -> Result<(u32, &'a [u8]), FromBytesError> {
fn decode(bytes: &[u8]) -> Result<(u32, &[u8]), FromBytesError> {
match nom::combinator::all_consuming(multihash::<nom::error::Error<&[u8]>>)(bytes) {
Ok((_rest, multihash)) => {
debug_assert!(_rest.is_empty());
Expand Down
73 changes: 32 additions & 41 deletions lib/src/network/basic_peering_strategy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -951,52 +951,43 @@ where
type Item = (&'a TChainId, UnassignSlotsAndBan<TInstant>);

fn next(&mut self) -> Option<Self::Item> {
let Some(inner_iter) = self.inner_iter.as_mut() else {
return None;
let inner_iter = self.inner_iter.as_mut()?;
let (&(_, chain_index), state) = inner_iter.next()?;

let return_value = match state {
PeerChainState::Banned { expires } if *expires >= self.when_unban => {
// Ban is already long enough. Nothing to do.
return Some((
&self.chains[chain_index],
UnassignSlotsAndBan::AlreadyBanned {
when_unban: expires.clone(),
ban_extended: false,
},
));
}
PeerChainState::Banned { .. } => UnassignSlotsAndBan::AlreadyBanned {
when_unban: self.when_unban.clone(),
ban_extended: true,
},
PeerChainState::Assignable => UnassignSlotsAndBan::Banned { had_slot: false },
PeerChainState::Slot => UnassignSlotsAndBan::Banned { had_slot: true },
};

loop {
let Some((&(_, chain_index), state)) = inner_iter.next() else {
return None;
};

let return_value = match state {
PeerChainState::Banned { expires } if *expires >= self.when_unban => {
// Ban is already long enough. Nothing to do.
return Some((
&self.chains[chain_index],
UnassignSlotsAndBan::AlreadyBanned {
when_unban: expires.clone(),
ban_extended: false,
},
));
}
PeerChainState::Banned { .. } => UnassignSlotsAndBan::AlreadyBanned {
when_unban: self.when_unban.clone(),
ban_extended: true,
},
PeerChainState::Assignable => UnassignSlotsAndBan::Banned { had_slot: false },
PeerChainState::Slot => UnassignSlotsAndBan::Banned { had_slot: true },
};

let _was_in = self.peers_chains_by_state.remove(&(
chain_index,
state.clone(),
self.peer_id_index,
));
debug_assert!(_was_in);
let _was_in =
self.peers_chains_by_state
.remove(&(chain_index, state.clone(), self.peer_id_index));
debug_assert!(_was_in);

*state = PeerChainState::Banned {
expires: self.when_unban.clone(),
};
*state = PeerChainState::Banned {
expires: self.when_unban.clone(),
};

let _was_inserted =
self.peers_chains_by_state
.insert((chain_index, state.clone(), self.peer_id_index));
debug_assert!(_was_inserted);
let _was_inserted =
self.peers_chains_by_state
.insert((chain_index, state.clone(), self.peer_id_index));
debug_assert!(_was_inserted);

break Some((&self.chains[chain_index], return_value));
}
Some((&self.chains[chain_index], return_value))
}

fn size_hint(&self) -> (usize, Option<usize>) {
Expand Down
2 changes: 1 addition & 1 deletion lib/src/trie/prefix_proof/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ fn regression_test_174() {
.map(|e| e.0)
.collect::<Vec<_>>();
expected.sort();
entries.sort_by(|(key1, _), (key2, _)| key1.cmp(&key2));
entries.sort_by(|(key1, _), (key2, _)| key1.cmp(key2));
assert_eq!(
entries.into_iter().map(|(key, _)| key).collect::<Vec<_>>(),
expected
Expand Down
14 changes: 6 additions & 8 deletions lib/src/trie/trie_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -673,14 +673,12 @@ mod tests {

#[test]
fn no_children_no_storage_value() {
assert!(matches!(
super::encode(super::Decoded {
children: [None::<&'static [u8]>; 16],
storage_value: super::StorageValue::None,
partial_key: core::iter::empty()
}),
Ok(_)
));
assert!(super::encode(super::Decoded {
children: [None::<&'static [u8]>; 16],
storage_value: super::StorageValue::None,
partial_key: core::iter::empty()
})
.is_ok());

assert!(matches!(
super::encode(super::Decoded {
Expand Down
6 changes: 3 additions & 3 deletions lib/src/verify/body_only.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use crate::{header, util, verify::inherents};
use alloc::vec::Vec;
use core::{iter, time::Duration};

pub const EXECUTE_BLOCK_FUNCTION_NAME: &'static str = "Core_execute_block";
pub const EXECUTE_BLOCK_FUNCTION_NAME: &str = "Core_execute_block";

/// Returns a list of buffers that, when concatenated together, forms the parameter to pass to
/// the `Core_execute_block` function in order to verify the inherents of a block.
Expand Down Expand Up @@ -84,7 +84,7 @@ pub enum ExecuteBlockOutputError {
NotEmpty,
}

pub const CHECK_INHERENTS_FUNCTION_NAME: &'static str = "BlockBuilder_check_inherents";
pub const CHECK_INHERENTS_FUNCTION_NAME: &str = "BlockBuilder_check_inherents";

/// Returns a list of buffers that, when concatenated together, forms the parameter to pass to
/// the `BlockBuilder_check_inherents` function in order to verify the inherents of a block.
Expand Down Expand Up @@ -127,7 +127,7 @@ pub fn check_inherents_parameter<'a>(
)),
]
.into_iter()
.flat_map(|i| i))
.flatten())
}

/// Checks the output of the `BlockBuilder_check_inherents` runtime call.
Expand Down
18 changes: 9 additions & 9 deletions light-base/src/json_rpc_service/background.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2804,8 +2804,8 @@ pub(super) async fn run<TPlat: PlatformRef>(
// Filter by start key and count.
let results_to_client = cache_entry
.iter()
.filter(|&k| start_key.as_ref().map_or(true, |s| *k > *s))
.cloned()
.filter(|k| start_key.as_ref().map_or(true, |s| *k > *s))
.map(methods::HexString)
.take(usize::try_from(*count).unwrap_or(usize::MAX))
.collect::<Vec<_>>();
Expand Down Expand Up @@ -3404,7 +3404,7 @@ pub(super) async fn run<TPlat: PlatformRef>(
&request_id_json,
parse::ErrorResponse::ServerError(
-32000,
&format!("Failed to decode runtime output"),
&"Failed to decode runtime output".to_string(),
),
None,
))
Expand Down Expand Up @@ -3610,8 +3610,8 @@ pub(super) async fn run<TPlat: PlatformRef>(
// Filter by start key and count.
let results_to_client = final_results
.iter()
.filter(|&k| start_key.as_ref().map_or(true, |s| *k > *s))
.cloned()
.filter(|k| start_key.as_ref().map_or(true, |s| *k > *s))
.map(methods::HexString)
.take(usize::try_from(count).unwrap_or(usize::MAX))
.collect::<Vec<_>>();
Expand Down Expand Up @@ -3810,7 +3810,7 @@ pub(super) async fn run<TPlat: PlatformRef>(
finalized_block_runtime: finalized_block_runtime.as_ref().map(
|runtime| match runtime {
Ok(rt) => methods::MaybeRuntimeSpec::Valid {
spec: convert_runtime_version(&rt),
spec: convert_runtime_version(rt),
},
Err(error) => methods::MaybeRuntimeSpec::Invalid {
error: error.to_string(),
Expand Down Expand Up @@ -4012,7 +4012,7 @@ pub(super) async fn run<TPlat: PlatformRef>(
new_runtime: match &block.new_runtime {
Some(Ok(rt)) => {
Some(methods::MaybeRuntimeSpec::Valid {
spec: convert_runtime_version(&rt),
spec: convert_runtime_version(rt),
})
}
Some(Err(error)) => {
Expand Down Expand Up @@ -4831,7 +4831,7 @@ pub(super) async fn run<TPlat: PlatformRef>(
.block_headers_pending
.remove(&block_hash)
.into_iter()
.flat_map(|l| l)
.flatten()
{
// Note that we push_front in order to guarantee that the information is
// not removed from cache before the request is processed.
Expand All @@ -4853,7 +4853,7 @@ pub(super) async fn run<TPlat: PlatformRef>(
.block_headers_pending
.remove(&block_hash)
.into_iter()
.flat_map(|l| l)
.flatten()
{
let _ = me
.responses_tx
Expand Down Expand Up @@ -4882,7 +4882,7 @@ pub(super) async fn run<TPlat: PlatformRef>(
.block_runtimes_pending
.remove(&block_hash)
.into_iter()
.flat_map(|l| l)
.flatten()
{
// Note that we push_front in order to guarantee that the information is
// not removed from cache before the request is processed.
Expand All @@ -4904,7 +4904,7 @@ pub(super) async fn run<TPlat: PlatformRef>(
.block_runtimes_pending
.remove(&block_hash)
.into_iter()
.flat_map(|l| l)
.flatten()
{
let _ = me
.responses_tx
Expand Down
11 changes: 5 additions & 6 deletions light-base/src/network_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,8 +313,7 @@ impl<TPlat: PlatformRef> NetworkServiceChain<TPlat> {
pub async fn subscribe(&self) -> async_channel::Receiver<Event> {
let (tx, rx) = async_channel::bounded(128);

let _ = self
.messages_tx
self.messages_tx
.send(ToBackgroundChain::Subscribe { sender: tx })
.await
.unwrap();
Expand Down Expand Up @@ -1537,7 +1536,7 @@ async fn background_task<TPlat: PlatformRef>(mut task: BackgroundTask<TPlat>) {
for peer in &peers_to_send {
match task
.network
.gossip_send_transaction(&peer, chain_id, &transaction)
.gossip_send_transaction(peer, chain_id, &transaction)
{
Ok(()) => peers_sent.push(peer.to_base58()),
Err(QueueNotificationError::QueueFull) => {
Expand Down Expand Up @@ -1849,11 +1848,11 @@ async fn background_task<TPlat: PlatformRef>(mut task: BackgroundTask<TPlat>) {
.get_mut(&(chain_id, peer_id.clone()))
.unwrap();
if let Ok(decoded) = header::decode(
&decoded_announce.scale_encoded_header,
decoded_announce.scale_encoded_header,
task.network[chain_id].block_number_bytes,
) {
link.best_block_hash = header::hash_from_scale_encoded_header(
&decoded_announce.scale_encoded_header,
decoded_announce.scale_encoded_header,
);
link.best_block_number = decoded.number;
}
Expand Down Expand Up @@ -2665,7 +2664,7 @@ async fn background_task<TPlat: PlatformRef>(mut task: BackgroundTask<TPlat>) {
.collect();
let remote_tls_certificate_multihash = [18u8, 32]
.into_iter()
.chain(remote_certificate_sha256.into_iter().copied())
.chain(remote_certificate_sha256.iter().copied())
.collect();

let (connection_id, connection_task) =
Expand Down
13 changes: 3 additions & 10 deletions light-base/src/platform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,7 @@

use alloc::borrow::Cow;
use core::{
fmt,
future::Future,
net::{IpAddr, Ipv4Addr, Ipv6Addr},
ops,
panic::UnwindSafe,
pin::Pin,
str,
time::Duration,
fmt, future::Future, net::IpAddr, ops, panic::UnwindSafe, pin::Pin, str, time::Duration,
};
use futures_util::future;

Expand Down Expand Up @@ -381,12 +374,12 @@ impl<'a> From<&'a Address<'a>> for ConnectionType {
Address::WebSocketIp {
ip: IpAddr::V4(ip), ..
} => ConnectionType::WebSocketIpv4 {
remote_is_localhost: Ipv4Addr::from(*ip).is_loopback(),
remote_is_localhost: ip.is_loopback(),
},
Address::WebSocketIp {
ip: IpAddr::V6(ip), ..
} => ConnectionType::WebSocketIpv6 {
remote_is_localhost: Ipv6Addr::from(*ip).is_loopback(),
remote_is_localhost: ip.is_loopback(),
},
Address::WebSocketDns {
hostname, secure, ..
Expand Down
Loading

0 comments on commit 69449dc

Please sign in to comment.