Skip to content

Commit

Permalink
fix clippy and fmt warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
simonjiao committed Apr 3, 2024
1 parent 60df70e commit 0c971ef
Show file tree
Hide file tree
Showing 61 changed files with 109 additions and 170 deletions.
4 changes: 1 addition & 3 deletions account/api/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,14 @@ use starcoin_types::account_config::token_code::TokenCode;
use starcoin_types::sign_message::{SignedMessage, SigningMessage};
use starcoin_types::transaction::{RawUserTransaction, SignedUserTransaction};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Default)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum AccountProviderStrategy {
#[default]
RPC,
Local,
PrivateKey,
}


pub trait AccountProvider {
fn create_account(&self, password: String) -> Result<AccountInfo>;

Expand Down
2 changes: 1 addition & 1 deletion account/src/account_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ pub fn test_wallet_account() -> Result<()> {
let hash_value = HashValue::sha3_256_of(&public_key.to_bytes());
let key = AuthenticationKey::new(*HashValue::sha3_256_of(&public_key.to_bytes()).as_ref());

let sign = vec![
let sign = [
227, 94, 250, 168, 43, 200, 137, 74, 61, 254, 197, 71, 245, 135, 201, 43, 222, 190, 56,
235, 247, 254, 56, 247, 108, 36, 250, 192, 143, 236, 101, 153, 61, 241, 129, 47, 38, 146,
213, 9, 79, 56, 90, 210, 179, 53, 73, 208, 248, 231, 22, 9, 55, 177, 154, 212, 248, 2, 66,
Expand Down
4 changes: 3 additions & 1 deletion chain/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1284,7 +1284,9 @@ impl BlockChain {
let pre_total_difficulty = parent_status
.map(|status| status.total_difficulty())
.unwrap_or_default();
let total_difficulty = pre_total_difficulty + header.difficulty();
let total_difficulty = pre_total_difficulty
.checked_add(header.difficulty())
.ok_or(format_err!("failed to calculate total difficulty"))?;
block_accumulator.append(&[block_id])?;

let txn_accumulator_info: AccumulatorInfo = txn_accumulator.get_info();
Expand Down
2 changes: 1 addition & 1 deletion chain/tests/test_txn_info_and_proof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ fn test_transaction_info_and_proof() -> Result<()> {
//put the genesis txn, the genesis block metadata txn do not generate txn info

all_txns.push(Transaction::UserTransaction(
genesis_block.body.transactions.get(0).cloned().unwrap(),
genesis_block.body.transactions.first().cloned().unwrap(),
));

(0..block_count).for_each(|_block_idx| {
Expand Down
4 changes: 2 additions & 2 deletions cmd/db-exporter/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -862,7 +862,7 @@ pub fn apply_block(
}

if let Some(last_block) = blocks.last() {
let start = blocks.get(0).unwrap().header().number();
let start = blocks.first().unwrap().header().number();
let end = last_block.header().number();
println!(
"current number {}, import [{},{}] block number",
Expand Down Expand Up @@ -2138,7 +2138,7 @@ pub fn apply_turbo_stm_block(
}

if let Some(last_block) = blocks.last() {
let start = blocks.get(0).unwrap().header().number();
let start = blocks.first().unwrap().header().number();
let end = last_block.header().number();
println!(
"current number {}, import [{},{}] block number",
Expand Down
7 changes: 2 additions & 5 deletions cmd/starcoin/src/account/sign_multisig_txn_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,11 +146,8 @@ impl CommandAction for GenerateMultisigTxnCommand {
unreachable!()
};
let mut raw_txn_view: RawUserTransactionView = raw_txn.clone().try_into()?;
raw_txn_view.decoded_payload = Some(
ctx.state()
.decode_txn_payload(raw_txn.payload())?
.try_into()?,
);
raw_txn_view.decoded_payload =
Some(ctx.state().decode_txn_payload(raw_txn.payload())?.into());
// Use `eprintln` instead of `println`, for keep the cli stdout's format(such as json) is not broken by print.
eprintln!(
"Prepare to sign the transaction: \n {}",
Expand Down
3 changes: 1 addition & 2 deletions cmd/starcoin/src/cli_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,7 @@ impl CliState {
raw_txn: raw_txn.clone(),
})?;
let mut raw_txn_view: RawUserTransactionView = raw_txn.clone().try_into()?;
raw_txn_view.decoded_payload =
Some(self.decode_txn_payload(raw_txn.payload())?.try_into()?);
raw_txn_view.decoded_payload = Some(self.decode_txn_payload(raw_txn.payload())?.into());

let mut execute_result = ExecuteResultView::new(raw_txn_view, raw_txn.to_hex(), dry_output);
if only_dry_run
Expand Down
8 changes: 4 additions & 4 deletions cmd/tx-factory/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ fn main() {
let batch_size = opts.batch_size;

let mut connected = RpcClient::connect_ipc(opts.ipc_path.clone());
while matches!(connected, Err(_)) {
while connected.is_err() {
std::thread::sleep(Duration::from_millis(1000));
connected = RpcClient::connect_ipc(opts.ipc_path.clone());
info!("re connecting...");
Expand Down Expand Up @@ -316,7 +316,7 @@ impl TxnMocker {
let result = self.client.submit_transaction(user_txn);

// increase sequence number if added in pool.
if matches!(result, Ok(_)) {
if result.is_ok() {
self.next_sequence_number += 1;
}
if blocking {
Expand Down Expand Up @@ -374,7 +374,7 @@ impl TxnMocker {
let txn_hash = user_txn.id();
let result = self.client.submit_transaction(user_txn);

if matches!(result, Ok(_)) && blocking {
if result.is_ok() && blocking {
self.client.watch_txn(
txn_hash,
Some(Duration::from_secs(self.watch_timeout as u64)),
Expand Down Expand Up @@ -495,7 +495,7 @@ impl TxnMocker {
expiration_timestamp,
)?;
let result = self.submit_txn(txn, self.account_address, true);
if matches!(result, Ok(_)) {
if result.is_ok() {
info!("account transfer submit ok.");
} else {
info!("error: {:?}", result);
Expand Down
22 changes: 11 additions & 11 deletions commons/forkable-jellyfish-merkle/src/jellyfish_merkle_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ fn test_batch_insertion() {
let tree = JellyfishMerkleTree::new(&db);
let mut batches2 = vec![];

for (_idx, sub_vec) in batches.iter().enumerate() {
for sub_vec in batches.iter() {
for x in sub_vec {
batches2.push(vec![(x.0, Some(x.1.clone()))]);
}
Expand Down Expand Up @@ -555,7 +555,7 @@ fn test_put_blob_sets() {
let mut root_hashes_one_by_one = vec![];
let mut batch_one_by_one = TreeUpdateBatch::default();
{
let mut iter = keys.clone().into_iter().zip(values.clone().into_iter());
let mut iter = keys.clone().into_iter().zip(values.clone());
let db = MockTreeStore::default();
let tree = JellyfishMerkleTree::new(&db);

Expand All @@ -579,7 +579,7 @@ fn test_put_blob_sets() {
}
}
{
let mut iter = keys.into_iter().zip(values.into_iter());
let mut iter = keys.into_iter().zip(values);
let db = MockTreeStore::default();
let tree = JellyfishMerkleTree::new(&db);
let mut blob_sets = vec![];
Expand Down Expand Up @@ -649,7 +649,7 @@ fn many_versions_get_proof_and_verify_tree_root(seed: &[u8], num_versions: usize

let mut roots = vec![];
let mut current_root = None;
for (_idx, kvs) in kvs.iter().enumerate() {
for kvs in kvs.iter() {
let (root, batch) = tree
.put_blob_set(current_root, vec![(kvs.0.into(), kvs.1.clone())])
.unwrap();
Expand All @@ -659,7 +659,7 @@ fn many_versions_get_proof_and_verify_tree_root(seed: &[u8], num_versions: usize
}

// Update value of all keys
for (_idx, kvs) in kvs.iter().enumerate() {
for kvs in kvs.iter() {
let (root, batch) = tree
.put_blob_set(current_root, vec![(kvs.0.into(), kvs.2.clone())])
.unwrap();
Expand Down Expand Up @@ -764,8 +764,8 @@ proptest! {
}
}

fn test_existent_keys_impl<'a>(
tree: &JellyfishMerkleTree<'a, HashValueKey, MockTreeStore>,
fn test_existent_keys_impl(
tree: &JellyfishMerkleTree<'_, HashValueKey, MockTreeStore>,
root_hash: HashValue,
existent_kvs: &HashMap<HashValueKey, Blob>,
) {
Expand All @@ -778,8 +778,8 @@ fn test_existent_keys_impl<'a>(
}
}

fn test_nonexistent_keys_impl<'a>(
tree: &JellyfishMerkleTree<'a, HashValueKey, MockTreeStore>,
fn test_nonexistent_keys_impl(
tree: &JellyfishMerkleTree<'_, HashValueKey, MockTreeStore>,
root_hash: HashValue,
nonexistent_keys: &[HashValueKey],
) {
Expand All @@ -792,8 +792,8 @@ fn test_nonexistent_keys_impl<'a>(
}
}

fn test_nonexistent_key_value_update_impl<'a>(
tree: &JellyfishMerkleTree<'a, HashValueKey, MockTreeStore>,
fn test_nonexistent_key_value_update_impl(
tree: &JellyfishMerkleTree<'_, HashValueKey, MockTreeStore>,
db: &MockTreeStore,
root_hash: HashValue,
noneexistent_kv: (HashValue, Blob),
Expand Down
2 changes: 1 addition & 1 deletion commons/forkable-jellyfish-merkle/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ where
blob_sets: Vec<Vec<(K, Option<Blob>)>>,
) -> Result<(Vec<HashValue>, TreeUpdateBatch<K>)> {
let mut tree_cache = TreeCache::new(self.reader, state_root_hash);
for (_idx, blob_set) in blob_sets.into_iter().enumerate() {
for blob_set in blob_sets.into_iter() {
assert!(
!blob_set.is_empty(),
"Transactions that output empty write set should not be included.",
Expand Down
4 changes: 2 additions & 2 deletions commons/service-registry/src/bus/sys_bus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ impl SysBus {
M: Send + Clone + Debug + 'static,
{
let type_id = TypeId::of::<M>();
let topic_subscribes = self.subscriptions.entry(type_id).or_insert_with(Vec::new);
let topic_subscribes = self.subscriptions.entry(type_id).or_default();
debug!("do_subscribe: {:?}", subscription);
topic_subscribes.push(Box::new(subscription));
}
Expand Down Expand Up @@ -249,7 +249,7 @@ mod tests {
let mut bus = SysBus::new();
let receiver = bus.oneshot::<Message>();
assert_eq!(1, bus.len_by_type::<Message>());
let job = task::spawn(async { receiver.await });
let job = task::spawn(receiver);
Delay::new(Duration::from_millis(10)).await;
bus.broadcast(Message {});
let result = job.await;
Expand Down
5 changes: 1 addition & 4 deletions config/src/api_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,7 @@ impl FromStr for Api {
}
}

#[derive(Debug, Clone)]
#[derive(Default)]
#[derive(Debug, Clone, Default)]
pub enum ApiSet {
// Unsafe context (like jsonrpc over http)
#[default]
Expand All @@ -98,8 +97,6 @@ pub enum ApiSet {
List(HashSet<Api>),
}



impl PartialEq for ApiSet {
fn eq(&self, other: &Self) -> bool {
self.list_apis() == other.list_apis()
Expand Down
2 changes: 0 additions & 2 deletions config/src/genesis_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,6 @@ impl BuiltinNetworkID {
}
}



impl From<BuiltinNetworkID> for ChainNetwork {
fn from(network: BuiltinNetworkID) -> Self {
ChainNetwork::new(
Expand Down
4 changes: 2 additions & 2 deletions config/src/network_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,8 @@ impl Seeds {
}
pub fn merge(&mut self, other: &Seeds) {
let mut seeds = HashSet::new();
seeds.extend(self.0.clone().into_iter());
seeds.extend(other.0.clone().into_iter());
seeds.extend(self.0.clone());
seeds.extend(other.0.clone());
let mut seeds: Vec<MultiaddrWithPeerId> = seeds.into_iter().collect();
//keep order in config
seeds.sort();
Expand Down
2 changes: 1 addition & 1 deletion consensus/src/consensus_test.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0

#![allow(clippy::integer_arithmetic)]
#![allow(clippy::arithmetic_side_effects)]

use crate::consensus::Consensus;
use crate::difficulty::{get_next_target_helper, BlockDiffInfo};
Expand Down
2 changes: 1 addition & 1 deletion executor/benchmark/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ impl TransactionGenerator {

/// Generates transactions that allocate `init_account_balance` to every account.
fn gen_create_account_transactions(&mut self, init_account_balance: u64, block_size: usize) {
for (_i, block) in self.accounts.chunks(block_size).enumerate() {
for block in self.accounts.chunks(block_size) {
self.net.time_service().sleep(1000);

let mut transactions = Vec::with_capacity(block_size + 1);
Expand Down
2 changes: 1 addition & 1 deletion genesis/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,7 @@ mod tests {
storage2.get_accumulator_store(AccumulatorStoreType::Transaction),
);

let genesis_txn = genesis_block.body.transactions.get(0).cloned().unwrap();
let genesis_txn = genesis_block.body.transactions.first().cloned().unwrap();
assert_eq!(
txn_accumulator.get_leaf(0).unwrap().unwrap(),
storage1
Expand Down
2 changes: 1 addition & 1 deletion miner/src/create_block_template/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ where
pub fn insert_uncle(&mut self, uncle: BlockHeader) {
self.parent_uncle
.entry(uncle.parent_hash())
.or_insert_with(Vec::new)
.or_default()
.push(uncle.id());
self.uncles.insert(uncle.id(), uncle);
if let Some(metrics) = self.metrics.as_ref() {
Expand Down
1 change: 0 additions & 1 deletion network-p2p/derive/src/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ pub fn compute_args(method: &syn::TraitItemMethod) -> Punctuated<syn::FnArg, syn
_ => continue,
};
let syn::PathSegment { ident, .. } = &segments[0];
let ident = ident;
if *ident == "Self" {
continue;
}
Expand Down
5 changes: 1 addition & 4 deletions network-p2p/peerset/tests/fuzz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,7 @@ fn test_once() {
for _ in 0..2500 {
// Each of these weights corresponds to an action that we may perform.
let action_weights = [150, 90, 90, 30, 30, 1, 1, 4, 4];
match WeightedIndex::new(&action_weights)
.unwrap()
.sample(&mut rng)
{
match WeightedIndex::new(action_weights).unwrap().sample(&mut rng) {
// If we generate 0, poll the peerset.
0 => match Stream::poll_next(Pin::new(&mut peerset), cx) {
Poll::Ready(Some(Message::Connect { peer_id, .. })) => {
Expand Down
2 changes: 1 addition & 1 deletion network-p2p/src/peer_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ pub struct Node<'a>(&'a NodeInfo);
impl<'a> Node<'a> {
/// Returns the endpoint of an established connection to the peer.
pub fn endpoint(&self) -> Option<&'a ConnectedPoint> {
self.0.endpoints.get(0) // `endpoints` will trigger an exception if no item was pushed
self.0.endpoints.first() // `endpoints` will trigger an exception if no item was pushed
}

/// Returns the latest version information we know of.
Expand Down
2 changes: 2 additions & 0 deletions network-p2p/src/service_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,7 @@ const PROTOCOL_NAME: &str = "/starcoin/notify/1";
// }
//

#[allow(clippy::let_underscore_future)]
#[stest::test]
async fn test_handshake_fail() {
let protocol = ProtocolId::from("starcoin");
Expand Down Expand Up @@ -592,6 +593,7 @@ fn test_handshake_message() {
assert_eq!(status, status2);
}

#[allow(clippy::let_underscore_future)]
#[stest::test]
async fn test_support_protocol() {
let protocol = ProtocolId::from("starcoin");
Expand Down
9 changes: 3 additions & 6 deletions network/api/src/peer_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,7 @@ impl From<(PeerInfo, u64)> for PeerDetail {
}
}

#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize, JsonSchema)]
#[derive(Default)]
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize, JsonSchema, Default)]
pub enum PeerStrategy {
Random,
#[default]
Expand All @@ -95,8 +94,6 @@ pub enum PeerStrategy {
Avg,
}



impl std::fmt::Display for PeerStrategy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let display = match self {
Expand Down Expand Up @@ -434,7 +431,7 @@ impl PeerSelector {
}

if self.len() == 1 {
return self.details.lock().get(0).map(|peer| peer.peer_id());
return self.details.lock().first().map(|peer| peer.peer_id());
}

let mut random = rand::thread_rng();
Expand All @@ -461,7 +458,7 @@ impl PeerSelector {
pub fn first_peer(&self) -> Option<PeerInfo> {
self.details
.lock()
.get(0)
.first()
.map(|peer| peer.peer_info.clone())
}

Expand Down
2 changes: 1 addition & 1 deletion network/api/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ fn test_better_peer() {
peers.push(PeerInfo::random());
}

let first_peer = peers.get(0).cloned().expect("first peer must exist.");
let first_peer = peers.first().cloned().expect("first peer must exist.");

let peer_selector = PeerSelector::new(peers, PeerStrategy::default(), None);
let better_selector = peer_selector.betters(first_peer.total_difficulty(), 10);
Expand Down
Loading

0 comments on commit 0c971ef

Please sign in to comment.