diff --git a/substrate/bin/node-template/node/src/service.rs b/substrate/bin/node-template/node/src/service.rs index 2d1cc878b4..04eb2add27 100644 --- a/substrate/bin/node-template/node/src/service.rs +++ b/substrate/bin/node-template/node/src/service.rs @@ -156,7 +156,7 @@ pub fn new_full(config: Configuration) -> Result { // if the node isn't actively participating in consensus then it doesn't // need a keystore, regardless of which protocol we use below. let keystore = if role.is_authority() { - Some(keystore.clone() as sp_core::traits::BareCryptoStorePtr) + Some(keystore as sp_core::traits::BareCryptoStorePtr) } else { None }; @@ -182,11 +182,11 @@ pub fn new_full(config: Configuration) -> Result { let grandpa_config = sc_finality_grandpa::GrandpaParams { config: grandpa_config, link: grandpa_link, - network: network.clone(), - inherent_data_providers: inherent_data_providers.clone(), + network, + inherent_data_providers, telemetry_on_connect: Some(telemetry_on_connect_sinks.on_connect_stream()), voting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(), - prometheus_registry: prometheus_registry.clone(), + prometheus_registry, shared_voter_state: SharedVoterState::empty(), }; @@ -200,7 +200,7 @@ pub fn new_full(config: Configuration) -> Result { sc_finality_grandpa::setup_disabled_grandpa( client, &inherent_data_providers, - network.clone(), + network, )?; } @@ -221,7 +221,7 @@ pub fn new_light(config: Configuration) -> Result { let pool_api = sc_transaction_pool::LightChainApi::new( builder.client().clone(), - fetcher.clone(), + fetcher, ); let pool = Arc::new(sc_transaction_pool::BasicPool::new_light( builder.config().transaction_pool.clone(), diff --git a/substrate/bin/node/bench/src/tempdb.rs b/substrate/bin/node/bench/src/tempdb.rs index 770bafec6f..4020fd1029 100644 --- a/substrate/bin/node/bench/src/tempdb.rs +++ b/substrate/bin/node/bench/src/tempdb.rs @@ -124,7 +124,6 @@ impl Clone for TempDatabase { .map(|f_result| f_result.expect("failed to read file in seed db") .path() - .clone() ).collect(); fs_extra::copy_items( &self_db_files, diff --git a/substrate/bin/node/cli/src/service.rs b/substrate/bin/node/cli/src/service.rs index 5074bda665..e817bb2a8c 100644 --- a/substrate/bin/node/cli/src/service.rs +++ b/substrate/bin/node/cli/src/service.rs @@ -272,7 +272,7 @@ pub fn new_full_base( // if the node isn't actively participating in consensus then it doesn't // need a keystore, regardless of which protocol we use below. let keystore = if role.is_authority() { - Some(keystore.clone() as BareCryptoStorePtr) + Some(keystore as BareCryptoStorePtr) } else { None }; @@ -302,7 +302,7 @@ pub fn new_full_base( inherent_data_providers: inherent_data_providers.clone(), telemetry_on_connect: Some(telemetry_on_connect_sinks.on_connect_stream()), voting_rule: grandpa::VotingRulesBuilder::default().build(), - prometheus_registry: prometheus_registry.clone(), + prometheus_registry, shared_voter_state, }; @@ -403,7 +403,7 @@ pub fn new_light_base(config: Configuration) -> Result<( babe_block_import, None, Some(Box::new(finality_proof_import)), - client.clone(), + client, select_chain, inherent_data_providers.clone(), spawn_task_handle, diff --git a/substrate/bin/node/testing/src/bench.rs b/substrate/bin/node/testing/src/bench.rs index 6f351a7001..90e1a16eb1 100644 --- a/substrate/bin/node/testing/src/bench.rs +++ b/substrate/bin/node/testing/src/bench.rs @@ -118,7 +118,6 @@ impl Clone for BenchDb { .map(|f_result| f_result.expect("failed to read file in seed db") .path() - .clone() ).collect(); fs_extra::copy_items( &seed_db_files, diff --git a/substrate/bin/utils/chain-spec-builder/src/main.rs b/substrate/bin/utils/chain-spec-builder/src/main.rs index 4fbcc1e850..2bfbb09527 100644 --- a/substrate/bin/utils/chain-spec-builder/src/main.rs +++ b/substrate/bin/utils/chain-spec-builder/src/main.rs @@ -131,7 +131,7 @@ fn generate_chain_spec( Default::default(), ); - chain_spec.as_json(false).map_err(|err| err.to_string()) + chain_spec.as_json(false).map_err(|err| err) } fn generate_authority_keys_and_store( diff --git a/substrate/client/api/src/in_mem.rs b/substrate/client/api/src/in_mem.rs index 9bfdcdd4d5..7d27326678 100644 --- a/substrate/client/api/src/in_mem.rs +++ b/substrate/client/api/src/in_mem.rs @@ -124,7 +124,7 @@ impl Clone for Blockchain { fn clone(&self) -> Self { let storage = Arc::new(RwLock::new(self.storage.read().clone())); Blockchain { - storage: storage.clone(), + storage, } } } @@ -155,7 +155,7 @@ impl Blockchain { aux: HashMap::new(), })); Blockchain { - storage: storage.clone(), + storage, } } @@ -346,7 +346,7 @@ impl HeaderMetadata for Blockchain { fn header_metadata(&self, hash: Block::Hash) -> Result, Self::Error> { self.header(BlockId::hash(hash))?.map(|header| CachedHeaderMetadata::from(&header)) - .ok_or(sp_blockchain::Error::UnknownBlock(format!("header not found: {}", hash))) + .ok_or_else(|| sp_blockchain::Error::UnknownBlock(format!("header not found: {}", hash))) } fn insert_header_metadata(&self, _hash: Block::Hash, _metadata: CachedHeaderMetadata) { diff --git a/substrate/client/cli/src/config.rs b/substrate/client/cli/src/config.rs index fa3f09116c..efda45a0ec 100644 --- a/substrate/client/cli/src/config.rs +++ b/substrate/client/cli/src/config.rs @@ -158,7 +158,7 @@ pub trait CliConfiguration: Sized { fn database_cache_size(&self) -> Result> { Ok(self.database_params() .map(|x| x.database_cache_size()) - .unwrap_or(Default::default())) + .unwrap_or_default()) } /// Get the database backend variant. @@ -195,7 +195,7 @@ pub trait CliConfiguration: Sized { fn state_cache_size(&self) -> Result { Ok(self.import_params() .map(|x| x.state_cache_size()) - .unwrap_or(Default::default())) + .unwrap_or_default()) } /// Get the state cache child ratio (if any). @@ -212,7 +212,7 @@ pub trait CliConfiguration: Sized { fn pruning(&self, unsafe_pruning: bool, role: &Role) -> Result { self.pruning_params() .map(|x| x.pruning(unsafe_pruning, role)) - .unwrap_or(Ok(Default::default())) + .unwrap_or_else(|| Ok(Default::default())) } /// Get the chain ID (string). @@ -236,7 +236,7 @@ pub trait CliConfiguration: Sized { fn wasm_method(&self) -> Result { Ok(self.import_params() .map(|x| x.wasm_method()) - .unwrap_or(Default::default())) + .unwrap_or_default()) } /// Get the execution strategies. @@ -251,7 +251,7 @@ pub trait CliConfiguration: Sized { Ok(self .import_params() .map(|x| x.execution_strategies(is_dev, is_validator)) - .unwrap_or(Default::default())) + .unwrap_or_default()) } /// Get the RPC HTTP address (`None` if disabled). @@ -365,7 +365,7 @@ pub trait CliConfiguration: Sized { fn tracing_targets(&self) -> Result> { Ok(self.import_params() .map(|x| x.tracing_targets()) - .unwrap_or(Default::default())) + .unwrap_or_else(|| Default::default())) } /// Get the TracingReceiver value from the current object @@ -375,7 +375,7 @@ pub trait CliConfiguration: Sized { fn tracing_receiver(&self) -> Result { Ok(self.import_params() .map(|x| x.tracing_receiver()) - .unwrap_or(Default::default())) + .unwrap_or_default()) } /// Get the node key from the current object @@ -385,7 +385,7 @@ pub trait CliConfiguration: Sized { fn node_key(&self, net_config_dir: &PathBuf) -> Result { self.node_key_params() .map(|x| x.node_key(net_config_dir)) - .unwrap_or(Ok(Default::default())) + .unwrap_or_else(|| Ok(Default::default())) } /// Get maximum runtime instances diff --git a/substrate/client/cli/src/params/import_params.rs b/substrate/client/cli/src/params/import_params.rs index c2fb34f90e..e60779429b 100644 --- a/substrate/client/cli/src/params/import_params.rs +++ b/substrate/client/cli/src/params/import_params.rs @@ -113,7 +113,7 @@ impl ImportParams { default }; - exec.execution.unwrap_or(strat.unwrap_or(default)).into() + exec.execution.unwrap_or_else(|| strat.unwrap_or(default)).into() }; let default_execution_import_block = if is_validator { diff --git a/substrate/client/cli/src/params/keystore_params.rs b/substrate/client/cli/src/params/keystore_params.rs index 8b20dd247a..a6eb438cc0 100644 --- a/substrate/client/cli/src/params/keystore_params.rs +++ b/substrate/client/cli/src/params/keystore_params.rs @@ -94,7 +94,7 @@ impl KeystoreParams { let path = self .keystore_path .clone() - .unwrap_or(base_path.join(DEFAULT_KEYSTORE_CONFIG_PATH)); + .unwrap_or_else(|| base_path.join(DEFAULT_KEYSTORE_CONFIG_PATH)); Ok(KeystoreConfig::Path { path, password }) } diff --git a/substrate/client/consensus/aura/src/lib.rs b/substrate/client/consensus/aura/src/lib.rs index 19bc3bae6c..8763239771 100644 --- a/substrate/client/consensus/aura/src/lib.rs +++ b/substrate/client/consensus/aura/src/lib.rs @@ -165,7 +165,7 @@ pub fn start_aura( CAW: CanAuthorWith + Send, { let worker = AuraWorker { - client: client.clone(), + client, block_import: Arc::new(Mutex::new(block_import)), env, keystore, @@ -839,7 +839,7 @@ pub fn import_queue( initialize_authorities_cache(&*client)?; let verifier = AuraVerifier { - client: client.clone(), + client, inherent_data_providers, phantom: PhantomData, }; diff --git a/substrate/client/db/src/lib.rs b/substrate/client/db/src/lib.rs index 7cfde1e1d9..086db73728 100644 --- a/substrate/client/db/src/lib.rs +++ b/substrate/client/db/src/lib.rs @@ -512,7 +512,7 @@ impl HeaderMetadata for BlockchainDb { header_metadata.clone(), ); header_metadata - }).ok_or(ClientError::UnknownBlock(format!("header not found in db: {}", hash))) + }).ok_or_else(|| ClientError::UnknownBlock(format!("header not found in db: {}", hash))) }, Ok) } diff --git a/substrate/client/db/src/light.rs b/substrate/client/db/src/light.rs index 3dc6453cd9..139ecf3b22 100644 --- a/substrate/client/db/src/light.rs +++ b/substrate/client/db/src/light.rs @@ -200,7 +200,7 @@ impl HeaderMetadata for LightStorage { header_metadata.clone(), ); header_metadata - }).ok_or(ClientError::UnknownBlock(format!("header not found in db: {}", hash))) + }).ok_or_else(|| ClientError::UnknownBlock(format!("header not found in db: {}", hash))) }, Ok) } diff --git a/substrate/client/db/src/utils.rs b/substrate/client/db/src/utils.rs index c25b978be0..168ab9bbb7 100644 --- a/substrate/client/db/src/utils.rs +++ b/substrate/client/db/src/utils.rs @@ -181,8 +181,8 @@ pub fn insert_hash_to_key_mapping, H: AsRef<[u8]> + Clone>( ) -> sp_blockchain::Result<()> { transaction.set_from_vec( key_lookup_col, - hash.clone().as_ref(), - number_and_hash_to_lookup_key(number, hash)?, + hash.as_ref(), + number_and_hash_to_lookup_key(number, hash.clone())?, ); Ok(()) } diff --git a/substrate/client/executor/runtime-test/src/lib.rs b/substrate/client/executor/runtime-test/src/lib.rs index 4962c558ea..41c9c6d9cb 100644 --- a/substrate/client/executor/runtime-test/src/lib.rs +++ b/substrate/client/executor/runtime-test/src/lib.rs @@ -353,7 +353,7 @@ fn execute_sandboxed( Memory::new() can't return a Error qed" ), }; - env_builder.add_memory("env", "memory", memory.clone()); + env_builder.add_memory("env", "memory", memory); env_builder }; diff --git a/substrate/client/executor/src/native_executor.rs b/substrate/client/executor/src/native_executor.rs index b1eb504d5a..0aeec98067 100644 --- a/substrate/client/executor/src/native_executor.rs +++ b/substrate/client/executor/src/native_executor.rs @@ -336,7 +336,7 @@ impl CodeExecutor for NativeExecutor { let res = with_externalities_safe(&mut **ext, move || (call)()) .and_then(|r| r .map(NativeOrEncoded::Native) - .map_err(|s| Error::ApiError(s.to_string())) + .map_err(|s| Error::ApiError(s)) ); Ok(res) diff --git a/substrate/client/executor/wasmi/src/lib.rs b/substrate/client/executor/wasmi/src/lib.rs index e4b4aca409..1632aa3c18 100644 --- a/substrate/client/executor/wasmi/src/lib.rs +++ b/substrate/client/executor/wasmi/src/lib.rs @@ -234,7 +234,6 @@ impl<'a> Sandbox for FunctionExecutor<'a> { table.get(dispatch_thunk_id) .map_err(|_| "dispatch_thunk_idx is out of the table bounds")? .ok_or_else(|| "dispatch_thunk_idx points on an empty table entry")? - .clone() }; let guest_env = match sandbox::GuestEnvironment::decode(&self.sandbox_store, raw_env_def) { diff --git a/substrate/client/finality-grandpa/src/communication/mod.rs b/substrate/client/finality-grandpa/src/communication/mod.rs index b7bbad9f8e..a8bfb84416 100644 --- a/substrate/client/finality-grandpa/src/communication/mod.rs +++ b/substrate/client/finality-grandpa/src/communication/mod.rs @@ -701,8 +701,8 @@ impl Sink> for OutgoingMessages keystore.local_id().clone(), self.round, self.set_id, - ).ok_or( - Error::Signing(format!( + ).ok_or_else( + || Error::Signing(format!( "Failed to sign GRANDPA vote for round {} targetting {:?}", self.round, target_hash )) )?; diff --git a/substrate/client/keystore/src/lib.rs b/substrate/client/keystore/src/lib.rs index 7fec32bae2..f337f64d1c 100644 --- a/substrate/client/keystore/src/lib.rs +++ b/substrate/client/keystore/src/lib.rs @@ -310,7 +310,7 @@ impl BareCryptoStore for Store { .fold(Vec::new(), |mut v, k| { v.push(CryptoTypePublicPair(sr25519::CRYPTO_ID, k.clone())); v.push(CryptoTypePublicPair(ed25519::CRYPTO_ID, k.clone())); - v.push(CryptoTypePublicPair(ecdsa::CRYPTO_ID, k.clone())); + v.push(CryptoTypePublicPair(ecdsa::CRYPTO_ID, k)); v })) } diff --git a/substrate/client/network-gossip/src/state_machine.rs b/substrate/client/network-gossip/src/state_machine.rs index da07bde3e7..80a0f9e70b 100644 --- a/substrate/client/network-gossip/src/state_machine.rs +++ b/substrate/client/network-gossip/src/state_machine.rs @@ -180,7 +180,7 @@ impl ConsensusGossip { let validator = self.validator.clone(); let mut context = NetworkContext { gossip: self, network }; - validator.new_peer(&mut context, &who, role.clone()); + validator.new_peer(&mut context, &who, role); } fn register_message_hashed( diff --git a/substrate/client/network/src/block_requests.rs b/substrate/client/network/src/block_requests.rs index 8f5116657a..1aa557d6cd 100644 --- a/substrate/client/network/src/block_requests.rs +++ b/substrate/client/network/src/block_requests.rs @@ -409,7 +409,7 @@ where }, body: if get_body { self.chain.block_body(&BlockId::Hash(hash))? - .unwrap_or(Vec::new()) + .unwrap_or_default() .iter_mut() .map(|extrinsic| extrinsic.encode()) .collect() @@ -418,7 +418,7 @@ where }, receipt: Vec::new(), message_queue: Vec::new(), - justification: justification.unwrap_or(Vec::new()), + justification: justification.unwrap_or_default(), is_empty_justification, }; diff --git a/substrate/client/network/src/error.rs b/substrate/client/network/src/error.rs index b87e495983..d5a4024ef5 100644 --- a/substrate/client/network/src/error.rs +++ b/substrate/client/network/src/error.rs @@ -32,7 +32,7 @@ pub enum Error { /// Io error Io(std::io::Error), /// Client error - Client(sp_blockchain::Error), + Client(Box), /// The same bootnode (based on address) is registered with two different peer ids. #[display( fmt = "The same bootnode (`{}`) is registered with two different peer ids: `{}` and `{}`", diff --git a/substrate/client/network/src/finality_requests.rs b/substrate/client/network/src/finality_requests.rs index 9bb3cfec74..de737cdd20 100644 --- a/substrate/client/network/src/finality_requests.rs +++ b/substrate/client/network/src/finality_requests.rs @@ -206,7 +206,7 @@ where let finality_proof = if let Some(provider) = &self.finality_proof_provider { provider .prove_finality(block_hash, &request.request)? - .unwrap_or(Vec::new()) + .unwrap_or_default() } else { log::error!("Answering a finality proof request while finality provider is empty"); return Err(From::from("Empty finality proof provider".to_string())) diff --git a/substrate/client/network/src/protocol/generic_proto/behaviour.rs b/substrate/client/network/src/protocol/generic_proto/behaviour.rs index 0e56b03b7a..215eb73933 100644 --- a/substrate/client/network/src/protocol/generic_proto/behaviour.rs +++ b/substrate/client/network/src/protocol/generic_proto/behaviour.rs @@ -806,7 +806,7 @@ impl GenericProto { debug!(target: "sub-libp2p", "PSM => Accept({:?}, {:?}): Obsolete incoming, sending back dropped", index, incoming.peer_id); debug!(target: "sub-libp2p", "PSM <= Dropped({:?})", incoming.peer_id); - self.peerset.dropped(incoming.peer_id.clone()); + self.peerset.dropped(incoming.peer_id); return } diff --git a/substrate/client/network/src/protocol/sync/extra_requests.rs b/substrate/client/network/src/protocol/sync/extra_requests.rs index 6d688c130f..d025b86b25 100644 --- a/substrate/client/network/src/protocol/sync/extra_requests.rs +++ b/substrate/client/network/src/protocol/sync/extra_requests.rs @@ -141,7 +141,7 @@ impl ExtraRequests { request, ); } - self.failed_requests.entry(request).or_insert(Vec::new()).push((who, Instant::now())); + self.failed_requests.entry(request).or_default().push((who, Instant::now())); self.pending_requests.push_front(request); } else { trace!(target: "sync", "No active {} request to {:?}", diff --git a/substrate/client/network/test/src/lib.rs b/substrate/client/network/test/src/lib.rs index d0f1d4752b..30508711a6 100644 --- a/substrate/client/network/test/src/lib.rs +++ b/substrate/client/network/test/src/lib.rs @@ -678,7 +678,7 @@ pub trait TestNetFactory: Sized { protocol_id: ProtocolId::from(&b"test-protocol-name"[..]), import_queue, block_announce_validator: config.block_announce_validator - .unwrap_or(Box::new(DefaultBlockAnnounceValidator)), + .unwrap_or_else(|| Box::new(DefaultBlockAnnounceValidator)), metrics_registry: None, }).unwrap(); diff --git a/substrate/client/rpc/src/state/state_light.rs b/substrate/client/rpc/src/state/state_light.rs index ec275a2d78..c7e218541a 100644 --- a/substrate/client/rpc/src/state/state_light.rs +++ b/substrate/client/rpc/src/state/state_light.rs @@ -539,7 +539,7 @@ fn resolve_header>( maybe_header.then(move |result| ready(result.and_then(|maybe_header| - maybe_header.ok_or(ClientError::UnknownBlock(format!("{}", block))) + maybe_header.ok_or_else(|| ClientError::UnknownBlock(format!("{}", block))) ).map_err(client_err)), ) } diff --git a/substrate/client/service/src/builder.rs b/substrate/client/service/src/builder.rs index 6f46b8bbb7..fe8fdcef13 100644 --- a/substrate/client/service/src/builder.rs +++ b/substrate/client/service/src/builder.rs @@ -438,7 +438,7 @@ impl ServiceBuilder<(), (), (), (), (), (), (), (), (), (), ()> { backend, task_manager, keystore, - fetcher: Some(fetcher.clone()), + fetcher: Some(fetcher), select_chain: None, import_queue: (), finality_proof_request_builder: None, @@ -1286,7 +1286,7 @@ fn gen_handler( client.clone(), subscriptions.clone(), remote_backend.clone(), - on_demand.clone() + on_demand, ); (chain, state, child_state) @@ -1298,15 +1298,15 @@ fn gen_handler( }; let author = sc_rpc::author::Author::new( - client.clone(), - transaction_pool.clone(), + client, + transaction_pool, subscriptions, - keystore.clone(), + keystore, deny_unsafe, ); - let system = system::System::new(system_info, system_rpc_tx.clone(), deny_unsafe); + let system = system::System::new(system_info, system_rpc_tx, deny_unsafe); - let maybe_offchain_rpc = offchain_storage.clone() + let maybe_offchain_rpc = offchain_storage .map(|storage| { let offchain = sc_rpc::offchain::Offchain::new(storage, deny_unsafe); // FIXME: Use plain Option (don't collect into HashMap) when we upgrade to jsonrpc 14.1 @@ -1357,7 +1357,7 @@ fn build_network( { let transaction_pool_adapter = Arc::new(TransactionPoolAdapter { imports_external_transactions: !matches!(config.role, Role::Light), - pool: transaction_pool.clone(), + pool: transaction_pool, client: client.clone(), }); @@ -1391,8 +1391,8 @@ fn build_network( chain: client.clone(), finality_proof_provider, finality_proof_request_builder, - on_demand: on_demand.clone(), - transaction_pool: transaction_pool_adapter.clone() as _, + on_demand: on_demand, + transaction_pool: transaction_pool_adapter as _, import_queue: Box::new(import_queue), protocol_id, block_announce_validator, @@ -1407,7 +1407,7 @@ fn build_network( let future = build_network_future( config.role.clone(), network_mut, - client.clone(), + client, network_status_sinks.clone(), system_rpc_rx, has_bootnodes, diff --git a/substrate/client/service/src/client/block_rules.rs b/substrate/client/service/src/client/block_rules.rs index 247d09197b..e862379a56 100644 --- a/substrate/client/service/src/client/block_rules.rs +++ b/substrate/client/service/src/client/block_rules.rs @@ -52,8 +52,8 @@ impl BlockRules { bad_blocks: BadBlocks, ) -> Self { Self { - bad: bad_blocks.unwrap_or(HashSet::new()), - forks: fork_blocks.unwrap_or(vec![]).into_iter().collect(), + bad: bad_blocks.unwrap_or_else(|| HashSet::new()), + forks: fork_blocks.unwrap_or_else(|| vec![]).into_iter().collect(), } } diff --git a/substrate/client/service/test/src/lib.rs b/substrate/client/service/test/src/lib.rs index ac95dd11e8..b0dd2c0e25 100644 --- a/substrate/client/service/test/src/lib.rs +++ b/substrate/client/service/test/src/lib.rs @@ -518,7 +518,7 @@ pub fn sync( let temp = tempdir_with_prefix("substrate-sync-test"); let mut network = TestNet::new( &temp, - spec.clone(), + spec, (0..NUM_FULL_NODES).map(|_| { |cfg| full_builder(cfg) }), (0..NUM_LIGHT_NODES).map(|_| { |cfg| light_builder(cfg) }), // Note: this iterator is empty but we can't just use `iter::empty()`, otherwise @@ -592,7 +592,7 @@ pub fn consensus( let temp = tempdir_with_prefix("substrate-consensus-test"); let mut network = TestNet::new( &temp, - spec.clone(), + spec, (0..NUM_FULL_NODES / 2).map(|_| { |cfg| full_builder(cfg).map(|s| (s, ())) }), (0..NUM_LIGHT_NODES / 2).map(|_| { |cfg| light_builder(cfg) }), authorities.into_iter().map(|key| (key, { |cfg| full_builder(cfg).map(|s| (s, ())) })), diff --git a/substrate/client/transaction-pool/graph/src/base_pool.rs b/substrate/client/transaction-pool/graph/src/base_pool.rs index 25da341e67..81d8e802c2 100644 --- a/substrate/client/transaction-pool/graph/src/base_pool.rs +++ b/substrate/client/transaction-pool/graph/src/base_pool.rs @@ -278,7 +278,7 @@ impl BasePool, ) -> error::Result> { if self.is_imported(&tx.hash) { - return Err(error::Error::AlreadyImported(Box::new(tx.hash.clone()))) + return Err(error::Error::AlreadyImported(Box::new(tx.hash))) } let tx = WaitingTransaction::new( diff --git a/substrate/client/transaction-pool/graph/src/ready.rs b/substrate/client/transaction-pool/graph/src/ready.rs index b98512b05d..cbdb250789 100644 --- a/substrate/client/transaction-pool/graph/src/ready.rs +++ b/substrate/client/transaction-pool/graph/src/ready.rs @@ -538,7 +538,7 @@ impl Iterator for BestIterator { } } - return Some(best.transaction.clone()) + return Some(best.transaction) } } } diff --git a/substrate/client/transaction-pool/src/api.rs b/substrate/client/transaction-pool/src/api.rs index a14d5b0db1..c6671fd5bd 100644 --- a/substrate/client/transaction-pool/src/api.rs +++ b/substrate/client/transaction-pool/src/api.rs @@ -305,7 +305,7 @@ impl sc_transaction_graph::ChainApi for fn block_body(&self, id: &BlockId) -> Self::BodyFuture { let header = self.client.header(*id) - .and_then(|h| h.ok_or(sp_blockchain::Error::UnknownBlock(format!("{}", id)))); + .and_then(|h| h.ok_or_else(|| sp_blockchain::Error::UnknownBlock(format!("{}", id)))); let header = match header { Ok(header) => header, Err(err) => { diff --git a/substrate/frame/balances/src/lib.rs b/substrate/frame/balances/src/lib.rs index 3056cd1975..0bd57e3828 100644 --- a/substrate/frame/balances/src/lib.rs +++ b/substrate/frame/balances/src/lib.rs @@ -1092,7 +1092,7 @@ impl, I: Instance> Currency for Module where // defensive only: overflow should never happen, however in case it does, then this // operation is a no-op. - account.free = account.free.checked_add(&value).ok_or(Self::PositiveImbalance::zero())?; + account.free = account.free.checked_add(&value).ok_or_else(|| Self::PositiveImbalance::zero())?; Ok(PositiveImbalance::new(value)) }).unwrap_or_else(|x| x) @@ -1153,7 +1153,7 @@ impl, I: Instance> Currency for Module where }; account.free = value; Ok(imbalance) - }).unwrap_or(SignedImbalance::Positive(Self::PositiveImbalance::zero())) + }).unwrap_or_else(|_| SignedImbalance::Positive(Self::PositiveImbalance::zero())) } } diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index 67e2a4375e..f6327f7f2d 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -801,7 +801,7 @@ where fn rent_allowance(&self) -> BalanceOf { storage::rent_allowance::(&self.ctx.self_account) - .unwrap_or(>::max_value()) // Must never be triggered actually + .unwrap_or_else(|_| >::max_value()) // Must never be triggered actually } fn block_number(&self) -> T::BlockNumber { self.block_number } diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 6194e3a694..4b3a48119f 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -648,7 +648,7 @@ impl Module { let cfg = Config::preload(); let vm = WasmVm::new(&cfg.schedule); let loader = WasmLoader::new(&cfg.schedule); - let mut ctx = ExecutionContext::top_level(origin.clone(), &cfg, &vm, &loader); + let mut ctx = ExecutionContext::top_level(origin, &cfg, &vm, &loader); func(&mut ctx, gas_meter) } } diff --git a/substrate/frame/contracts/src/rent.rs b/substrate/frame/contracts/src/rent.rs index a3f582810a..908faca9a6 100644 --- a/substrate/frame/contracts/src/rent.rs +++ b/substrate/frame/contracts/src/rent.rs @@ -104,7 +104,7 @@ fn compute_fee_per_block( effective_storage_size .checked_mul(&T::RentByteFee::get()) - .unwrap_or(>::max_value()) + .unwrap_or_else(|| >::max_value()) } /// Returns amount of funds available to consume by rent mechanism. @@ -179,7 +179,7 @@ fn consider_case( let dues = fee_per_block .checked_mul(&blocks_passed.saturated_into::().into()) - .unwrap_or(>::max_value()); + .unwrap_or_else(|| >::max_value()); let insufficient_rent = rent_budget < dues; // If the rent payment cannot be withdrawn due to locks on the account balance, then evict the diff --git a/substrate/frame/elections-phragmen/src/lib.rs b/substrate/frame/elections-phragmen/src/lib.rs index e3ecb6ea22..50c5de9bc0 100644 --- a/substrate/frame/elections-phragmen/src/lib.rs +++ b/substrate/frame/elections-phragmen/src/lib.rs @@ -607,7 +607,7 @@ decl_module! { // returns NoMember error in case of error. let _ = Self::remove_and_replace_member(&who)?; T::Currency::unreserve(&who, T::CandidacyBond::get()); - Self::deposit_event(RawEvent::MemberRenounced(who.clone())); + Self::deposit_event(RawEvent::MemberRenounced(who)); }, Renouncing::RunnerUp => { let mut runners_up_with_stake = Self::runners_up(); @@ -1002,7 +1002,7 @@ impl Module { ); T::ChangeMembers::change_members_sorted( &incoming, - &outgoing.clone(), + &outgoing, &new_members_ids, ); T::ChangeMembers::set_prime(prime); diff --git a/substrate/frame/multisig/src/lib.rs b/substrate/frame/multisig/src/lib.rs index cbe6f2054c..f8f6e8ed63 100644 --- a/substrate/frame/multisig/src/lib.rs +++ b/substrate/frame/multisig/src/lib.rs @@ -295,12 +295,12 @@ decl_module! { ensure!(!other_signatories.is_empty(), Error::::TooFewSignatories); let other_signatories_len = other_signatories.len(); ensure!(other_signatories_len < max_sigs, Error::::TooManySignatories); - let signatories = Self::ensure_sorted_and_insert(other_signatories, who.clone())?; + let signatories = Self::ensure_sorted_and_insert(other_signatories, who)?; let id = Self::multi_account_id(&signatories, 1); let call_len = call.using_encoded(|c| c.len()); - let result = call.dispatch(RawOrigin::Signed(id.clone()).into()); + let result = call.dispatch(RawOrigin::Signed(id).into()); result.map(|post_dispatch_info| post_dispatch_info.actual_weight .map(|actual_weight| weight_of::as_multi_threshold_1::( diff --git a/substrate/frame/offences/benchmarking/src/lib.rs b/substrate/frame/offences/benchmarking/src/lib.rs index b47c14296a..1aa9fed85b 100644 --- a/substrate/frame/offences/benchmarking/src/lib.rs +++ b/substrate/frame/offences/benchmarking/src/lib.rs @@ -257,7 +257,7 @@ benchmarks! { .flat_map(|reporter| vec![ frame_system::Event::::NewAccount(reporter.clone()).into(), ::Event::from( - pallet_balances::Event::::Endowed(reporter.clone(), (reward_amount / r).into()) + pallet_balances::Event::::Endowed(reporter, (reward_amount / r).into()) ).into() ]); diff --git a/substrate/frame/scored-pool/src/lib.rs b/substrate/frame/scored-pool/src/lib.rs index 35c36b0319..90d4aca4e4 100644 --- a/substrate/frame/scored-pool/src/lib.rs +++ b/substrate/frame/scored-pool/src/lib.rs @@ -355,7 +355,7 @@ decl_module! { // if there is already an element with `score`, we insert // right before that. if not, the search returns a location // where we can insert while maintaining order. - let item = (who.clone(), Some(score.clone())); + let item = (who, Some(score.clone())); let location = pool .binary_search_by_key( &Reverse(score), diff --git a/substrate/frame/staking/fuzzer/src/submit_solution.rs b/substrate/frame/staking/fuzzer/src/submit_solution.rs index 7293cf2389..6812a739c4 100644 --- a/substrate/frame/staking/fuzzer/src/submit_solution.rs +++ b/substrate/frame/staking/fuzzer/src/submit_solution.rs @@ -162,7 +162,7 @@ fn main() { match mode { Mode::WeakerSubmission => { assert_eq!( - call.dispatch_bypass_filter(origin.clone().into()).unwrap_err().error, + call.dispatch_bypass_filter(origin.into()).unwrap_err().error, DispatchError::Module { index: 0, error: 16, diff --git a/substrate/frame/staking/src/benchmarking.rs b/substrate/frame/staking/src/benchmarking.rs index b2035c22b6..d92cd87179 100644 --- a/substrate/frame/staking/src/benchmarking.rs +++ b/substrate/frame/staking/src/benchmarking.rs @@ -61,7 +61,7 @@ pub fn create_validator_with_nominators( let validator_prefs = ValidatorPrefs { commission: Perbill::from_percent(50), }; - Staking::::validate(RawOrigin::Signed(v_controller.clone()).into(), validator_prefs)?; + Staking::::validate(RawOrigin::Signed(v_controller).into(), validator_prefs)?; let stash_lookup: ::Source = T::Lookup::unlookup(v_stash.clone()); points_total += 10; @@ -375,7 +375,7 @@ benchmarks! { for _ in 0 .. l { staking_ledger.unlocking.push(unlock_chunk.clone()) } - Ledger::::insert(controller.clone(), staking_ledger.clone()); + Ledger::::insert(controller, staking_ledger); let slash_amount = T::Currency::minimum_balance() * 10.into(); let balance_before = T::Currency::free_balance(&stash); }: { diff --git a/substrate/frame/staking/src/lib.rs b/substrate/frame/staking/src/lib.rs index be07c7e18a..dd4ad5fc7e 100644 --- a/substrate/frame/staking/src/lib.rs +++ b/substrate/frame/staking/src/lib.rs @@ -1626,7 +1626,7 @@ decl_module! { let era = Self::current_era().unwrap_or(0) + T::BondingDuration::get(); ledger.unlocking.push(UnlockChunk { value, era }); Self::update_ledger(&controller, &ledger); - Self::deposit_event(RawEvent::Unbonded(ledger.stash.clone(), value)); + Self::deposit_event(RawEvent::Unbonded(ledger.stash, value)); } } diff --git a/substrate/frame/staking/src/slashing.rs b/substrate/frame/staking/src/slashing.rs index 4e43b754b8..af9a92f16a 100644 --- a/substrate/frame/staking/src/slashing.rs +++ b/substrate/frame/staking/src/slashing.rs @@ -370,7 +370,7 @@ fn slash_nominators( let mut era_slash = as Store>::NominatorSlashInEra::get( &slash_era, stash, - ).unwrap_or(Zero::zero()); + ).unwrap_or_else(|| Zero::zero()); era_slash += own_slash_difference; diff --git a/substrate/frame/staking/src/testing_utils.rs b/substrate/frame/staking/src/testing_utils.rs index 27a2575eb0..02acd135e6 100644 --- a/substrate/frame/staking/src/testing_utils.rs +++ b/substrate/frame/staking/src/testing_utils.rs @@ -158,7 +158,7 @@ pub fn get_weak_solution( // self stake >::iter().for_each(|(who, _p)| { - *backing_stake_of.entry(who.clone()).or_insert(Zero::zero()) += + *backing_stake_of.entry(who.clone()).or_insert_with(|| Zero::zero()) += >::slashable_balance_of(&who) }); diff --git a/substrate/frame/support/procedural/src/storage/mod.rs b/substrate/frame/support/procedural/src/storage/mod.rs index 766141f5aa..b42639c30c 100644 --- a/substrate/frame/support/procedural/src/storage/mod.rs +++ b/substrate/frame/support/procedural/src/storage/mod.rs @@ -249,7 +249,7 @@ impl StorageLineDefExt { StorageLineTypeDef::DoubleMap(map) => map.value.clone(), }; let is_option = ext::extract_type_option(&query_type).is_some(); - let value_type = ext::extract_type_option(&query_type).unwrap_or(query_type.clone()); + let value_type = ext::extract_type_option(&query_type).unwrap_or_else(|| query_type.clone()); let module_runtime_generic = &def.module_runtime_generic; let module_runtime_trait = &def.module_runtime_trait; @@ -328,7 +328,7 @@ impl StorageLineDefExt { pub enum StorageLineTypeDef { Map(MapDef), - DoubleMap(DoubleMapDef), + DoubleMap(Box), Simple(syn::Type), } diff --git a/substrate/frame/support/procedural/src/storage/parse.rs b/substrate/frame/support/procedural/src/storage/parse.rs index 5a3bb3f40c..b1ef2916ad 100644 --- a/substrate/frame/support/procedural/src/storage/parse.rs +++ b/substrate/frame/support/procedural/src/storage/parse.rs @@ -198,7 +198,7 @@ impl_parse_for_opt!(DeclStorageBuild => keyword::build); #[derive(ToTokens, Debug)] enum DeclStorageType { Map(DeclStorageMap), - DoubleMap(DeclStorageDoubleMap), + DoubleMap(Box), Simple(syn::Type), } @@ -478,13 +478,13 @@ fn parse_storage_line_defs( } ), DeclStorageType::DoubleMap(map) => super::StorageLineTypeDef::DoubleMap( - super::DoubleMapDef { + Box::new(super::DoubleMapDef { hasher1: map.hasher1.inner.ok_or_else(no_hasher_error)?.into(), hasher2: map.hasher2.inner.ok_or_else(no_hasher_error)?.into(), key1: map.key1, key2: map.key2, value: map.value, - } + }) ), DeclStorageType::Simple(expr) => super::StorageLineTypeDef::Simple(expr), }; diff --git a/substrate/frame/support/procedural/tools/derive/src/lib.rs b/substrate/frame/support/procedural/tools/derive/src/lib.rs index ec5af13b67..6e5d6c896c 100644 --- a/substrate/frame/support/procedural/tools/derive/src/lib.rs +++ b/substrate/frame/support/procedural/tools/derive/src/lib.rs @@ -30,7 +30,7 @@ pub(crate) fn fields_idents( fields: impl Iterator, ) -> impl Iterator { fields.enumerate().map(|(ix, field)| { - field.ident.clone().map(|i| quote!{#i}).unwrap_or_else(|| { + field.ident.map(|i| quote!{#i}).unwrap_or_else(|| { let f_ix: syn::Ident = syn::Ident::new(&format!("f_{}", ix), Span::call_site()); quote!( #f_ix ) }) @@ -41,7 +41,7 @@ pub(crate) fn fields_access( fields: impl Iterator, ) -> impl Iterator { fields.enumerate().map(|(ix, field)| { - field.ident.clone().map(|i| quote!( #i )).unwrap_or_else(|| { + field.ident.map(|i| quote!( #i )).unwrap_or_else(|| { let f_ix: syn::Index = syn::Index { index: ix as u32, span: Span::call_site(), diff --git a/substrate/frame/system/src/offchain.rs b/substrate/frame/system/src/offchain.rs index 1290ca6378..6e6284b57f 100644 --- a/substrate/frame/system/src/offchain.rs +++ b/substrate/frame/system/src/offchain.rs @@ -185,7 +185,7 @@ impl, X> Signer let generic_public = C::GenericPublic::from(key); let public = generic_public.into(); let account_id = public.clone().into_account(); - Account::new(index, account_id, public.clone()) + Account::new(index, account_id, public) }) } } diff --git a/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs b/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs index 93ec09d0e6..8d9eeebef6 100644 --- a/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs +++ b/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs @@ -252,7 +252,7 @@ fn generate_native_call_generators(decl: &ItemTrait) -> Result { } FnArg::Typed(arg) }, - r => r.clone(), + r => r, }); let (impl_generics, ty_generics, where_clause) = decl.generics.split_for_impl(); diff --git a/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs b/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs index 97b159e6f0..85f5a1797b 100644 --- a/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs +++ b/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs @@ -417,7 +417,7 @@ fn extend_with_runtime_decl_path(mut trait_: Path) -> Path { }; let pos = trait_.segments.len() - 1; - trait_.segments.insert(pos, runtime.clone().into()); + trait_.segments.insert(pos, runtime.into()); trait_ } diff --git a/substrate/primitives/arithmetic/fuzzer/src/biguint.rs b/substrate/primitives/arithmetic/fuzzer/src/biguint.rs index 0966c12895..9763245f4c 100644 --- a/substrate/primitives/arithmetic/fuzzer/src/biguint.rs +++ b/substrate/primitives/arithmetic/fuzzer/src/biguint.rs @@ -48,8 +48,8 @@ fn main() { digits_u.reverse(); digits_v.reverse(); - let num_u = num_bigint::BigUint::new(digits_u.clone()); - let num_v = num_bigint::BigUint::new(digits_v.clone()); + let num_u = num_bigint::BigUint::new(digits_u); + let num_v = num_bigint::BigUint::new(digits_v); if check_digit_lengths(&u, &v, 4) { assert_eq!(u.cmp(&v), ue.cmp(&ve)); @@ -146,14 +146,14 @@ fn main() { // Division if v.len() == 1 && v.get(0) != 0 { - let w = u.clone().div_unit(v.get(0)); - let num_w = num_u.clone() / &num_v; + let w = u.div_unit(v.get(0)); + let num_w = num_u / &num_v; assert_biguints_eq(&w, &num_w); } else if u.len() > v.len() && v.len() > 0 { let num_remainder = num_u.clone() % num_v.clone(); - let (w, remainder) = u.clone().div(&v, return_remainder).unwrap(); - let num_w = num_u.clone() / &num_v; + let (w, remainder) = u.div(&v, return_remainder).unwrap(); + let num_w = num_u / &num_v; assert_biguints_eq(&w, &num_w); diff --git a/substrate/primitives/arithmetic/src/fixed_point.rs b/substrate/primitives/arithmetic/src/fixed_point.rs index 8653ee2c8f..59c237efb6 100644 --- a/substrate/primitives/arithmetic/src/fixed_point.rs +++ b/substrate/primitives/arithmetic/src/fixed_point.rs @@ -84,7 +84,7 @@ pub trait FixedPointNumber: fn saturating_from_integer(int: N) -> Self { let mut n: I129 = int.into(); n.value = n.value.saturating_mul(Self::DIV.saturated_into()); - Self::from_inner(from_i129(n).unwrap_or(to_bound(int, 0))) + Self::from_inner(from_i129(n).unwrap_or_else(|| to_bound(int, 0))) } /// Creates `self` from an integer number `int`. @@ -101,7 +101,7 @@ pub trait FixedPointNumber: if d == D::zero() { panic!("attempt to divide by zero") } - Self::checked_from_rational(n, d).unwrap_or(to_bound(n, d)) + Self::checked_from_rational(n, d).unwrap_or_else(|| to_bound(n, d)) } /// Creates `self` from a rational number. Equal to `n / d`. @@ -137,7 +137,7 @@ pub trait FixedPointNumber: /// /// Returns `N::min` or `N::max` if the result does not fit in `N`. fn saturating_mul_int(self, n: N) -> N { - self.checked_mul_int(n).unwrap_or(to_bound(self.into_inner(), n)) + self.checked_mul_int(n).unwrap_or_else(|| to_bound(self.into_inner(), n)) } /// Checked division for integer type `N`. Equal to `self / d`. @@ -160,7 +160,7 @@ pub trait FixedPointNumber: if d == N::zero() { panic!("attempt to divide by zero") } - self.checked_div_int(d).unwrap_or(to_bound(self.into_inner(), d)) + self.checked_div_int(d).unwrap_or_else(|| to_bound(self.into_inner(), d)) } /// Saturating multiplication for integer type `N`, adding the result back. @@ -183,7 +183,7 @@ pub trait FixedPointNumber: if inner >= Self::Inner::zero() { self } else { - Self::from_inner(inner.checked_neg().unwrap_or(Self::Inner::max_value())) + Self::from_inner(inner.checked_neg().unwrap_or_else(|| Self::Inner::max_value())) } } @@ -301,7 +301,7 @@ impl From for I129 { if n < N::zero() { let value: u128 = n.checked_neg() .map(|n| n.unique_saturated_into()) - .unwrap_or(N::max_value().unique_saturated_into().saturating_add(1)); + .unwrap_or_else(|| N::max_value().unique_saturated_into().saturating_add(1)); I129 { value, negative: true } } else { I129 { value: n.unique_saturated_into(), negative: false } @@ -399,7 +399,7 @@ macro_rules! implement_fixed { } fn saturating_mul(self, rhs: Self) -> Self { - self.checked_mul(&rhs).unwrap_or(to_bound(self.0, rhs.0)) + self.checked_mul(&rhs).unwrap_or_else(|| to_bound(self.0, rhs.0)) } fn saturating_pow(self, exp: usize) -> Self { diff --git a/substrate/primitives/consensus/common/src/import_queue/basic_queue.rs b/substrate/primitives/consensus/common/src/import_queue/basic_queue.rs index 8eb194841f..dddc332f43 100644 --- a/substrate/primitives/consensus/common/src/import_queue/basic_queue.rs +++ b/substrate/primitives/consensus/common/src/import_queue/basic_queue.rs @@ -108,7 +108,7 @@ impl ImportQueue for BasicQueue ) { let _ = self.sender .unbounded_send( - ToWorkerMsg::ImportJustification(who.clone(), hash, number, justification) + ToWorkerMsg::ImportJustification(who, hash, number, justification) ); } diff --git a/substrate/primitives/core/src/crypto.rs b/substrate/primitives/core/src/crypto.rs index b5bb0b935b..6250c67e3b 100644 --- a/substrate/primitives/core/src/crypto.rs +++ b/substrate/primitives/core/src/crypto.rs @@ -180,7 +180,7 @@ impl DeriveJunction { impl> From for DeriveJunction { fn from(j: T) -> DeriveJunction { let j = j.as_ref(); - let (code, hard) = if j.starts_with("/") { + let (code, hard) = if j.starts_with('/') { (&j[1..], true) } else { (j, false) diff --git a/substrate/primitives/core/src/offchain/testing.rs b/substrate/primitives/core/src/offchain/testing.rs index 9145477722..c939c5cfcc 100644 --- a/substrate/primitives/core/src/offchain/testing.rs +++ b/substrate/primitives/core/src/offchain/testing.rs @@ -359,7 +359,7 @@ impl offchain::Externalities for TestOffchainExt { if let Some(req) = state.requests.get_mut(&request_id) { let response = req.response .as_mut() - .expect(&format!("No response provided for request: {:?}", request_id)); + .unwrap_or_else(|| panic!("No response provided for request: {:?}", request_id)); if req.read >= response.len() { // Remove the pending request as per spec. diff --git a/substrate/primitives/core/src/testing.rs b/substrate/primitives/core/src/testing.rs index 1d88e1fad5..e512d3a39e 100644 --- a/substrate/primitives/core/src/testing.rs +++ b/substrate/primitives/core/src/testing.rs @@ -90,7 +90,7 @@ impl crate::traits::BareCryptoStore for KeyStore { v })) }) - .unwrap_or(Ok(vec![])) + .unwrap_or_else(|| Ok(vec![])) } fn sr25519_public_keys(&self, id: KeyTypeId) -> Vec { @@ -222,19 +222,19 @@ impl crate::traits::BareCryptoStore for KeyStore { ed25519::CRYPTO_ID => { let key_pair: ed25519::Pair = self .ed25519_key_pair(id, &ed25519::Public::from_slice(key.1.as_slice())) - .ok_or(Error::PairNotFound("ed25519".to_owned()))?; + .ok_or_else(|| Error::PairNotFound("ed25519".to_owned()))?; return Ok(key_pair.sign(msg).encode()); } sr25519::CRYPTO_ID => { let key_pair: sr25519::Pair = self .sr25519_key_pair(id, &sr25519::Public::from_slice(key.1.as_slice())) - .ok_or(Error::PairNotFound("sr25519".to_owned()))?; + .ok_or_else(|| Error::PairNotFound("sr25519".to_owned()))?; return Ok(key_pair.sign(msg).encode()); } ecdsa::CRYPTO_ID => { let key_pair: ecdsa::Pair = self .ecdsa_key_pair(id, &ecdsa::Public::from_slice(key.1.as_slice())) - .ok_or(Error::PairNotFound("ecdsa".to_owned()))?; + .ok_or_else(|| Error::PairNotFound("ecdsa".to_owned()))?; return Ok(key_pair.sign(msg).encode()); } _ => Err(Error::KeyNotSupported(id)) @@ -249,7 +249,7 @@ impl crate::traits::BareCryptoStore for KeyStore { ) -> Result { let transcript = make_transcript(transcript_data); let pair = self.sr25519_key_pair(key_type, public) - .ok_or(Error::PairNotFound("Not found".to_owned()))?; + .ok_or_else(|| Error::PairNotFound("Not found".to_owned()))?; let (inout, proof, _) = pair.as_ref().vrf_sign(transcript); Ok(VRFSignature { diff --git a/substrate/primitives/npos-elections/fuzzer/src/balance_solution.rs b/substrate/primitives/npos-elections/fuzzer/src/balance_solution.rs index e1bd3bd0a0..13f9b29706 100644 --- a/substrate/primitives/npos-elections/fuzzer/src/balance_solution.rs +++ b/substrate/primitives/npos-elections/fuzzer/src/balance_solution.rs @@ -114,7 +114,7 @@ fn main() { *stake_of_tree.get(who).unwrap() }; - let mut staked = assignment_ratio_to_staked(assignments.clone(), &stake_of); + let mut staked = assignment_ratio_to_staked(assignments, &stake_of); let winners = to_without_backing(winners); let mut support = build_support_map(winners.as_ref(), staked.as_ref()).0; diff --git a/substrate/primitives/npos-elections/src/lib.rs b/substrate/primitives/npos-elections/src/lib.rs index 592ed3b717..b3eb3ed6cc 100644 --- a/substrate/primitives/npos-elections/src/lib.rs +++ b/substrate/primitives/npos-elections/src/lib.rs @@ -416,7 +416,7 @@ pub fn seq_phragmen( n.load.n(), n.budget, c.approval_stake, - ).unwrap_or(Bounded::max_value()); + ).unwrap_or_else(|_| Bounded::max_value()); let temp_d = n.load.d(); let temp = Rational128::from(temp_n, temp_d); c.score = c.score.lazy_saturating_add(temp); @@ -470,14 +470,14 @@ pub fn seq_phragmen( n.load.n(), ) // If result cannot fit in u128. Not much we can do about it. - .unwrap_or(Bounded::max_value()); + .unwrap_or_else(|_| Bounded::max_value()); TryFrom::try_from(parts) // If the result cannot fit into R::Inner. Defensive only. This can // never happen. `desired_scale * e / n`, where `e / n < 1` always // yields a value smaller than `desired_scale`, which will fit into // R::Inner. - .unwrap_or(Bounded::max_value()) + .unwrap_or_else(|_| Bounded::max_value()) } else { // defensive only. Both edge and voter loads are built from // scores, hence MUST have the same denominator. diff --git a/substrate/primitives/npos-elections/src/reduce.rs b/substrate/primitives/npos-elections/src/reduce.rs index d0b4afe73d..6d458a5fff 100644 --- a/substrate/primitives/npos-elections/src/reduce.rs +++ b/substrate/primitives/npos-elections/src/reduce.rs @@ -362,11 +362,11 @@ fn reduce_all(assignments: &mut Vec>) -> u32 // create both. let voter_node = tree .entry(voter_id.clone()) - .or_insert(Node::new(voter_id).into_ref()) + .or_insert_with(|| Node::new(voter_id).into_ref()) .clone(); let target_node = tree .entry(target_id.clone()) - .or_insert(Node::new(target_id).into_ref()) + .or_insert_with(|| Node::new(target_id).into_ref()) .clone(); // If one exists but the other one doesn't, or if both does not, then set the existing diff --git a/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs b/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs index f27493ee4b..f9398b3ce5 100644 --- a/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs +++ b/substrate/primitives/state-machine/src/changes_trie/changes_iterator.rs @@ -46,7 +46,7 @@ pub fn key_changes<'a, H: Hasher, Number: BlockNumber>( key: &'a [u8], ) -> Result, String> { // we can't query any roots before root - let max = ::std::cmp::min(max.clone(), end.number.clone()); + let max = std::cmp::min(max, end.number.clone()); Ok(DrilldownIterator { essence: DrilldownIteratorEssence { @@ -85,7 +85,7 @@ pub fn key_changes_proof<'a, H: Hasher, Number: BlockNumber>( key: &[u8], ) -> Result>, String> where H::Out: Codec { // we can't query any roots before root - let max = ::std::cmp::min(max.clone(), end.number.clone()); + let max = std::cmp::min(max, end.number.clone()); let mut iter = ProvingDrilldownIterator { essence: DrilldownIteratorEssence { @@ -156,7 +156,7 @@ pub fn key_changes_proof_check_with_db<'a, H: Hasher, Number: BlockNumber>( key: &[u8] ) -> Result, String> where H::Out: Encode { // we can't query any roots before root - let max = ::std::cmp::min(max.clone(), end.number.clone()); + let max = std::cmp::min(max, end.number.clone()); DrilldownIterator { essence: DrilldownIteratorEssence { diff --git a/substrate/primitives/state-machine/src/ext.rs b/substrate/primitives/state-machine/src/ext.rs index cd4f83661b..d7d4bc145e 100644 --- a/substrate/primitives/state-machine/src/ext.rs +++ b/substrate/primitives/state-machine/src/ext.rs @@ -471,8 +471,8 @@ where let root = self .storage(prefixed_storage_key.as_slice()) .and_then(|k| Decode::decode(&mut &k[..]).ok()) - .unwrap_or( - empty_child_trie_root::>() + .unwrap_or_else( + || empty_child_trie_root::>() ); trace!(target: "state", "{:04x}: ChildRoot({})(cached) {}", self.id, @@ -512,8 +512,8 @@ where let root = self .storage(prefixed_storage_key.as_slice()) .and_then(|k| Decode::decode(&mut &k[..]).ok()) - .unwrap_or( - empty_child_trie_root::>() + .unwrap_or_else( + || empty_child_trie_root::>() ); trace!(target: "state", "{:04x}: ChildRoot({})(no_change) {}", self.id, diff --git a/substrate/primitives/state-machine/src/in_memory_backend.rs b/substrate/primitives/state-machine/src/in_memory_backend.rs index 8c0ae1ec8b..f211f60202 100644 --- a/substrate/primitives/state-machine/src/in_memory_backend.rs +++ b/substrate/primitives/state-machine/src/in_memory_backend.rs @@ -109,7 +109,7 @@ where Some(map) => insert_into_memory_db::( root, self.backend_storage_mut(), - map.clone().into_iter().chain(new_child_roots.into_iter()), + map.into_iter().chain(new_child_roots.into_iter()), ), None => insert_into_memory_db::( root, diff --git a/substrate/primitives/state-machine/src/proving_backend.rs b/substrate/primitives/state-machine/src/proving_backend.rs index 1f25005bc3..0888c561ca 100644 --- a/substrate/primitives/state-machine/src/proving_backend.rs +++ b/substrate/primitives/state-machine/src/proving_backend.rs @@ -71,7 +71,7 @@ impl<'a, S, H> ProvingBackendRecorder<'a, S, H> let storage_key = child_info.storage_key(); let root = self.storage(storage_key)? .and_then(|r| Decode::decode(&mut &r[..]).ok()) - .unwrap_or(empty_child_trie_root::>()); + .unwrap_or_else(|| empty_child_trie_root::>()); let mut read_overlay = S::Overlay::default(); let eph = Ephemeral::new( diff --git a/substrate/primitives/state-machine/src/trie_backend.rs b/substrate/primitives/state-machine/src/trie_backend.rs index 2d4ab782cb..e0a86bbd19 100644 --- a/substrate/primitives/state-machine/src/trie_backend.rs +++ b/substrate/primitives/state-machine/src/trie_backend.rs @@ -202,7 +202,7 @@ impl, H: Hasher> Backend for TrieBackend where let prefixed_storage_key = child_info.prefixed_storage_key(); let mut root = match self.storage(prefixed_storage_key.as_slice()) { Ok(value) => - value.and_then(|r| Decode::decode(&mut &r[..]).ok()).unwrap_or(default_root.clone()), + value.and_then(|r| Decode::decode(&mut &r[..]).ok()).unwrap_or_else(|| default_root.clone()), Err(e) => { warn!(target: "trie", "Failed to read child storage root: {}", e); default_root.clone() diff --git a/substrate/primitives/state-machine/src/trie_backend_essence.rs b/substrate/primitives/state-machine/src/trie_backend_essence.rs index c0ec15c137..72864e312b 100644 --- a/substrate/primitives/state-machine/src/trie_backend_essence.rs +++ b/substrate/primitives/state-machine/src/trie_backend_essence.rs @@ -171,7 +171,7 @@ impl, H: Hasher> TrieBackendEssence where H::Out: key: &[u8], ) -> Result, String> { let root = self.child_root(child_info)? - .unwrap_or(empty_child_trie_root::>().encode()); + .unwrap_or_else(|| empty_child_trie_root::>().encode()); let map_e = |e| format!("Trie lookup error: {}", e); @@ -186,7 +186,7 @@ impl, H: Hasher> TrieBackendEssence where H::Out: f: F, ) { let root = match self.child_root(child_info) { - Ok(v) => v.unwrap_or(empty_child_trie_root::>().encode()), + Ok(v) => v.unwrap_or_else(|| empty_child_trie_root::>().encode()), Err(e) => { debug!(target: "trie", "Error while iterating child storage: {}", e); return; @@ -211,7 +211,7 @@ impl, H: Hasher> TrieBackendEssence where H::Out: mut f: F, ) { let root_vec = match self.child_root(child_info) { - Ok(v) => v.unwrap_or(empty_child_trie_root::>().encode()), + Ok(v) => v.unwrap_or_else(|| empty_child_trie_root::>().encode()), Err(e) => { debug!(target: "trie", "Error while iterating child storage: {}", e); return; diff --git a/substrate/primitives/wasm-interface/src/lib.rs b/substrate/primitives/wasm-interface/src/lib.rs index d3ca4ecb5e..c432a96605 100644 --- a/substrate/primitives/wasm-interface/src/lib.rs +++ b/substrate/primitives/wasm-interface/src/lib.rs @@ -20,6 +20,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use sp_std::{ + vec, borrow::Cow, marker::PhantomData, mem, iter::Iterator, result, vec::Vec, }; @@ -275,8 +276,7 @@ impl PartialEq for dyn Function { pub trait FunctionContext { /// Read memory from `address` into a vector. fn read_memory(&self, address: Pointer, size: WordSize) -> Result> { - let mut vec = Vec::with_capacity(size as usize); - vec.resize(size as usize, 0); + let mut vec = vec![0; size as usize]; self.read_memory_into(address, &mut vec)?; Ok(vec) } diff --git a/substrate/test-utils/runtime/client/src/lib.rs b/substrate/test-utils/runtime/client/src/lib.rs index 4e9034fb4d..97cf13ed2a 100644 --- a/substrate/test-utils/runtime/client/src/lib.rs +++ b/substrate/test-utils/runtime/client/src/lib.rs @@ -348,7 +348,7 @@ pub fn new_light() -> ( let storage = sc_client_db::light::LightStorage::new_test(); let blockchain = Arc::new(sc_light::Blockchain::new(storage)); - let backend = Arc::new(LightBackend::new(blockchain.clone())); + let backend = Arc::new(LightBackend::new(blockchain)); let executor = new_native_executor(); let local_call_executor = client::LocalCallExecutor::new(backend.clone(), executor, sp_core::tasks::executor(), Default::default()); let call_executor = LightExecutor::new( diff --git a/substrate/test-utils/runtime/client/src/trait_tests.rs b/substrate/test-utils/runtime/client/src/trait_tests.rs index 537ff1197e..b240a42a78 100644 --- a/substrate/test-utils/runtime/client/src/trait_tests.rs +++ b/substrate/test-utils/runtime/client/src/trait_tests.rs @@ -284,7 +284,7 @@ pub fn test_children_for_backend(backend: Arc) where Default::default(), false, ).unwrap().build().unwrap().block; - client.import(BlockOrigin::Own, b4.clone()).unwrap(); + client.import(BlockOrigin::Own, b4).unwrap(); // // B2 -> C3 let mut builder = client.new_block_at( @@ -413,7 +413,7 @@ pub fn test_blockchain_query_by_number_gets_canonical(backend: Arc C3 let mut builder = client.new_block_at( @@ -429,7 +429,7 @@ pub fn test_blockchain_query_by_number_gets_canonical(backend: Arc D2 let mut builder = client.new_block_at( @@ -445,7 +445,7 @@ pub fn test_blockchain_query_by_number_gets_canonical(backend: Arc Self { GenesisConfig { changes_trie_config, - authorities: authorities.clone(), + authorities: authorities, balances: endowed_accounts.into_iter().map(|a| (a, balance)).collect(), heap_pages_override, extra_storage, diff --git a/substrate/utils/frame/rpc/system/src/lib.rs b/substrate/utils/frame/rpc/system/src/lib.rs index dc87f622fd..3204236236 100644 --- a/substrate/utils/frame/rpc/system/src/lib.rs +++ b/substrate/utils/frame/rpc/system/src/lib.rs @@ -263,7 +263,7 @@ fn adjust_nonce( // `provides` tag. And increment the nonce if we find a transaction // that matches the current one. let mut current_nonce = nonce.clone(); - let mut current_tag = (account.clone(), nonce.clone()).encode(); + let mut current_tag = (account.clone(), nonce).encode(); for tx in pool.ready() { log::debug!( target: "rpc", diff --git a/substrate/utils/wasm-builder/src/lib.rs b/substrate/utils/wasm-builder/src/lib.rs index 95b75c5867..c68921d05a 100644 --- a/substrate/utils/wasm-builder/src/lib.rs +++ b/substrate/utils/wasm-builder/src/lib.rs @@ -189,7 +189,7 @@ fn check_skip_build() -> bool { /// Write to the given `file` if the `content` is different. fn write_file_if_changed(file: PathBuf, content: String) { if fs::read_to_string(&file).ok().as_ref() != Some(&content) { - fs::write(&file, content).expect(&format!("Writing `{}` can not fail!", file.display())); + fs::write(&file, content).unwrap_or_else(|_| panic!("Writing `{}` can not fail!", file.display())); } } @@ -200,7 +200,7 @@ fn copy_file_if_changed(src: PathBuf, dst: PathBuf) { if src_file != dst_file { fs::copy(&src, &dst) - .expect(&format!("Copying `{}` to `{}` can not fail; qed", src.display(), dst.display())); + .unwrap_or_else(|_| panic!("Copying `{}` to `{}` can not fail; qed", src.display(), dst.display())); } } diff --git a/substrate/utils/wasm-builder/src/wasm_project.rs b/substrate/utils/wasm-builder/src/wasm_project.rs index 7df3524e8a..6f8f47881b 100644 --- a/substrate/utils/wasm-builder/src/wasm_project.rs +++ b/substrate/utils/wasm-builder/src/wasm_project.rs @@ -205,7 +205,7 @@ fn find_and_clear_workspace_members(wasm_workspace: &Path) -> Vec { .map(|d| d.into_path()) .filter(|p| p.is_dir()) .filter_map(|p| p.file_name().map(|f| f.to_owned()).and_then(|s| s.into_string().ok())) - .filter(|f| !f.starts_with(".") && f != "target") + .filter(|f| !f.starts_with('.') && f != "target") .collect::>(); let mut i = 0;