diff --git a/.cargo/config.toml b/.cargo/config.toml index 06328af71459c..de299a90971e4 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -10,5 +10,24 @@ rustflags = [ "-Aclippy::all", "-Dclippy::correctness", "-Aclippy::if-same-then-else", - "-Aclippy::clone-double-ref" + "-Aclippy::clone-double-ref", + "-Dclippy::complexity", + "-Aclippy::clone_on_copy", # Too common + "-Aclippy::needless_lifetimes", # Backward compat? + "-Aclippy::zero-prefixed-literal", # 00_1000_000 + "-Aclippy::type_complexity", # raison d'etre + "-Aclippy::nonminimal-bool", # maybe + "-Aclippy::borrowed-box", # Reasonable to fix this one + "-Aclippy::too-many-arguments", # (Turning this on would lead to) + "-Aclippy::unnecessary_cast", # Types may change + "-Aclippy::identity-op", # One case where we do 0 + + "-Aclippy::useless_conversion", # Types may change + "-Aclippy::unit_arg", # styalistic. + "-Aclippy::option-map-unit-fn", # styalistic + "-Aclippy::bind_instead_of_map", # styalistic + "-Aclippy::erasing_op", # E.g. 0 * DOLLARS + "-Aclippy::eq_op", # In tests we test equality. + "-Aclippy::while_immutable_condition", # false positives + "-Aclippy::needless_option_as_deref", # false positives + "-Aclippy::derivable_impls", # false positives ] diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 685d201d85983..2aee053ef4de3 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -350,7 +350,7 @@ cargo-clippy: <<: *docker-env <<: *test-refs script: - - SKIP_WASM_BUILD=1 env -u RUSTFLAGS cargo +nightly clippy + - SKIP_WASM_BUILD=1 env -u RUSTFLAGS cargo +nightly clippy --all-targets cargo-check-benches: stage: test diff --git a/bin/node-template/node/src/service.rs b/bin/node-template/node/src/service.rs index 92bd059e528a8..975a491cf4da1 100644 --- a/bin/node-template/node/src/service.rs +++ b/bin/node-template/node/src/service.rs @@ -60,7 +60,7 @@ pub fn new_partial( ServiceError, > { if config.keystore_remote.is_some() { - return Err(ServiceError::Other(format!("Remote Keystores are not supported."))) + return Err(ServiceError::Other("Remote Keystores are not supported.".into())) } let telemetry = config diff --git a/bin/node/inspect/src/lib.rs b/bin/node/inspect/src/lib.rs index 722a7903da4c2..ff1eecd219a97 100644 --- a/bin/node/inspect/src/lib.rs +++ b/bin/node/inspect/src/lib.rs @@ -261,7 +261,7 @@ impl FromStr for ExtrinsicAddres let index = it .next() - .ok_or_else(|| format!("Extrinsic index missing: example \"5:0\""))? + .ok_or("Extrinsic index missing: example \"5:0\"")? .parse() .map_err(|e| format!("Invalid index format: {}", e))?; diff --git a/client/chain-spec/src/chain_spec.rs b/client/chain-spec/src/chain_spec.rs index 98241255de55b..11e5b73fe77f8 100644 --- a/client/chain-spec/src/chain_spec.rs +++ b/client/chain-spec/src/chain_spec.rs @@ -223,7 +223,7 @@ impl ChainSpec { /// Network protocol id. pub fn protocol_id(&self) -> Option<&str> { - self.client_spec.protocol_id.as_ref().map(String::as_str) + self.client_spec.protocol_id.as_deref() } /// Additional loosly-typed properties of the chain. diff --git a/client/cli/src/arg_enums.rs b/client/cli/src/arg_enums.rs index 3e1ead609630a..c13361a9ac2ba 100644 --- a/client/cli/src/arg_enums.rs +++ b/client/cli/src/arg_enums.rs @@ -51,7 +51,7 @@ impl std::str::FromStr for WasmExecutionMethod { } #[cfg(not(feature = "wasmtime"))] { - Err(format!("`Compiled` variant requires the `wasmtime` feature to be enabled")) + Err("`Compiled` variant requires the `wasmtime` feature to be enabled".into()) } } else { Err(format!("Unknown variant `{}`, known variants: {:?}", s, Self::variants())) diff --git a/client/cli/src/commands/sign.rs b/client/cli/src/commands/sign.rs index 1b2fbba40ea16..8d331d7994595 100644 --- a/client/cli/src/commands/sign.rs +++ b/client/cli/src/commands/sign.rs @@ -70,7 +70,7 @@ fn sign( message: Vec, ) -> error::Result { let pair = utils::pair_from_suri::

(suri, password)?; - Ok(format!("{}", hex::encode(pair.sign(&message)))) + Ok(hex::encode(pair.sign(&message))) } #[cfg(test)] diff --git a/client/cli/src/commands/verify.rs b/client/cli/src/commands/verify.rs index bf03be1737d48..9ffd5d9d4844e 100644 --- a/client/cli/src/commands/verify.rs +++ b/client/cli/src/commands/verify.rs @@ -57,7 +57,7 @@ impl VerifyCmd { let message = utils::read_message(self.message.as_ref(), self.hex)?; let sig_data = utils::decode_hex(&self.sig)?; let uri = utils::read_uri(self.uri.as_ref())?; - let uri = if uri.starts_with("0x") { &uri[2..] } else { &uri }; + let uri = if let Some(uri) = uri.strip_prefix("0x") { uri } else { &uri }; with_crypto_scheme!(self.crypto_scheme.scheme, verify(sig_data, message, uri)) } diff --git a/client/cli/src/params/mod.rs b/client/cli/src/params/mod.rs index c7181840a8641..e6f81079263de 100644 --- a/client/cli/src/params/mod.rs +++ b/client/cli/src/params/mod.rs @@ -79,8 +79,8 @@ impl FromStr for BlockNumberOrHash { type Err = String; fn from_str(block_number: &str) -> Result { - if block_number.starts_with("0x") { - if let Some(pos) = &block_number[2..].chars().position(|c| !c.is_ascii_hexdigit()) { + if let Some(rest) = block_number.strip_prefix("0x") { + if let Some(pos) = rest.chars().position(|c| !c.is_ascii_hexdigit()) { Err(format!( "Expected block hash, found illegal hex character at position: {}", 2 + pos, diff --git a/client/consensus/common/src/block_import.rs b/client/consensus/common/src/block_import.rs index af54d54770f76..24fec9b974a4c 100644 --- a/client/consensus/common/src/block_import.rs +++ b/client/consensus/common/src/block_import.rs @@ -287,9 +287,9 @@ impl BlockImportParams { pub fn take_intermediate(&mut self, key: &[u8]) -> Result, Error> { let (k, v) = self.intermediates.remove_entry(key).ok_or(Error::NoIntermediate)?; - v.downcast::().or_else(|v| { + v.downcast::().map_err(|v| { self.intermediates.insert(k, v); - Err(Error::InvalidIntermediate) + Error::InvalidIntermediate }) } diff --git a/client/consensus/manual-seal/src/consensus/babe.rs b/client/consensus/manual-seal/src/consensus/babe.rs index b16bee816b172..6d86658cbf504 100644 --- a/client/consensus/manual-seal/src/consensus/babe.rs +++ b/client/consensus/manual-seal/src/consensus/babe.rs @@ -279,7 +279,7 @@ where // a quick check to see if we're in the authorities let epoch = self.epoch(parent, slot)?; let (authority, _) = self.authorities.first().expect("authorities is non-emptyp; qed"); - let has_authority = epoch.authorities.iter().find(|(id, _)| *id == *authority).is_some(); + let has_authority = epoch.authorities.iter().any(|(id, _)| *id == *authority); if !has_authority { log::info!(target: "manual-seal", "authority not found"); diff --git a/client/consensus/manual-seal/src/lib.rs b/client/consensus/manual-seal/src/lib.rs index 3e5ce5b2a4014..a057190f6b378 100644 --- a/client/consensus/manual-seal/src/lib.rs +++ b/client/consensus/manual-seal/src/lib.rs @@ -173,7 +173,7 @@ pub async fn run_manual_seal( env: &mut env, select_chain: &select_chain, block_import: &mut block_import, - consensus_data_provider: consensus_data_provider.as_ref().map(|p| &**p), + consensus_data_provider: consensus_data_provider.as_deref(), pool: pool.clone(), client: client.clone(), create_inherent_data_providers: &create_inherent_data_providers, @@ -408,8 +408,8 @@ mod tests { }) .await .unwrap(); - // assert that the background task returns ok - assert_eq!(rx.await.unwrap().unwrap(), ()); + // check that the background task returns ok: + rx.await.unwrap().unwrap(); } #[tokio::test] diff --git a/client/db/src/bench.rs b/client/db/src/bench.rs index a18e7942a54f4..fe31d31dfef9e 100644 --- a/client/db/src/bench.rs +++ b/client/db/src/bench.rs @@ -672,7 +672,6 @@ mod test { assert_eq!(rw_tracker.1, 0); assert_eq!(rw_tracker.2, 2); assert_eq!(rw_tracker.3, 0); - drop(rw_tracker); bench_state.wipe().unwrap(); } } diff --git a/client/db/src/lib.rs b/client/db/src/lib.rs index c570ca2f15fbe..19766d76048e9 100644 --- a/client/db/src/lib.rs +++ b/client/db/src/lib.rs @@ -1993,7 +1993,7 @@ impl sc_client_api::backend::Backend for Backend { }); let database_cache = MemorySize::from_bytes(0); let state_cache = - MemorySize::from_bytes((*&self.shared_cache).read().used_storage_cache_size()); + MemorySize::from_bytes(self.shared_cache.read().used_storage_cache_size()); let state_db = self.storage.state_db.memory_info(); Some(UsageInfo { @@ -2452,7 +2452,7 @@ pub(crate) mod tests { let storage = vec![(vec![1, 3, 5], None), (vec![5, 5, 5], Some(vec![4, 5, 6]))]; let (root, overlay) = op.old_state.storage_root( - storage.iter().map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..]))), + storage.iter().map(|(k, v)| (k.as_slice(), v.as_ref().map(|v| &v[..]))), state_version, ); op.update_db_storage(overlay).unwrap(); @@ -3000,7 +3000,7 @@ pub(crate) mod tests { let storage = vec![(b"test".to_vec(), Some(b"test2".to_vec()))]; let (root, overlay) = op.old_state.storage_root( - storage.iter().map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..]))), + storage.iter().map(|(k, v)| (k.as_slice(), v.as_ref().map(|v| &v[..]))), state_version, ); op.update_db_storage(overlay).unwrap(); diff --git a/client/db/src/offchain.rs b/client/db/src/offchain.rs index c6351a66a2350..4f0a77ce57566 100644 --- a/client/db/src/offchain.rs +++ b/client/db/src/offchain.rs @@ -92,7 +92,7 @@ impl sp_core::offchain::OffchainStorage for LocalStorage { { let _key_guard = key_lock.lock(); let val = self.db.get(columns::OFFCHAIN, &key); - is_set = val.as_ref().map(|x| &**x) == old_value; + is_set = val.as_deref() == old_value; if is_set { self.set(prefix, item_key, new_value) diff --git a/client/executor/src/integration_tests/mod.rs b/client/executor/src/integration_tests/mod.rs index 36339c31871d9..67e9a96cd6bae 100644 --- a/client/executor/src/integration_tests/mod.rs +++ b/client/executor/src/integration_tests/mod.rs @@ -126,7 +126,7 @@ fn call_in_wasm( let executor = crate::WasmExecutor::::new(execution_method, Some(1024), 8, None, 2); executor.uncached_call( - RuntimeBlob::uncompress_if_needed(&wasm_binary_unwrap()[..]).unwrap(), + RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(), ext, true, function, @@ -479,7 +479,7 @@ fn should_trap_when_heap_exhausted(wasm_method: WasmExecutionMethod) { let err = executor .uncached_call( - RuntimeBlob::uncompress_if_needed(&wasm_binary_unwrap()[..]).unwrap(), + RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(), &mut ext.ext(), true, "test_exhaust_heap", @@ -491,7 +491,7 @@ fn should_trap_when_heap_exhausted(wasm_method: WasmExecutionMethod) { } fn mk_test_runtime(wasm_method: WasmExecutionMethod, pages: u64) -> Arc { - let blob = RuntimeBlob::uncompress_if_needed(&wasm_binary_unwrap()[..]) + let blob = RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()) .expect("failed to create a runtime blob out of test runtime"); crate::wasm_runtime::create_wasm_runtime_with_code::( @@ -597,7 +597,7 @@ fn parallel_execution(wasm_method: WasmExecutionMethod) { assert_eq!( executor .uncached_call( - RuntimeBlob::uncompress_if_needed(&wasm_binary_unwrap()[..]).unwrap(), + RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(), &mut ext, true, "test_twox_128", @@ -691,7 +691,7 @@ fn panic_in_spawned_instance_panics_on_joining_its_result(wasm_method: WasmExecu let error_result = call_in_wasm("test_panic_in_spawned", &[], wasm_method, &mut ext).unwrap_err(); - assert!(format!("{}", error_result).contains("Spawned task")); + assert!(error_result.contains("Spawned task")); } test_wasm_execution!(memory_is_cleared_between_invocations); diff --git a/client/executor/src/lib.rs b/client/executor/src/lib.rs index fd127887dbc26..5cd04b9e4ee6a 100644 --- a/client/executor/src/lib.rs +++ b/client/executor/src/lib.rs @@ -82,7 +82,7 @@ mod tests { ); let res = executor .uncached_call( - RuntimeBlob::uncompress_if_needed(&wasm_binary_unwrap()[..]).unwrap(), + RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(), &mut ext, true, "test_empty_return", diff --git a/client/executor/src/wasm_runtime.rs b/client/executor/src/wasm_runtime.rs index cb6fba4e4dee5..0775755aff7cf 100644 --- a/client/executor/src/wasm_runtime.rs +++ b/client/executor/src/wasm_runtime.rs @@ -77,7 +77,7 @@ struct VersionedRuntime { impl VersionedRuntime { /// Run the given closure `f` with an instance of this runtime. - fn with_instance<'c, R, F>(&self, ext: &mut dyn Externalities, f: F) -> Result + fn with_instance(&self, ext: &mut dyn Externalities, f: F) -> Result where F: FnOnce( &Arc, diff --git a/client/executor/wasmtime/src/host.rs b/client/executor/wasmtime/src/host.rs index 5d02a836640ae..5da8ff3259031 100644 --- a/client/executor/wasmtime/src/host.rs +++ b/client/executor/wasmtime/src/host.rs @@ -195,7 +195,7 @@ impl<'a> Sandbox for HostContext<'a> { &mut self, instance_id: u32, export_name: &str, - args: &[u8], + mut args: &[u8], return_val: Pointer, return_val_len: u32, state: u32, @@ -203,7 +203,7 @@ impl<'a> Sandbox for HostContext<'a> { trace!(target: "sp-sandbox", "invoke, instance_idx={}", instance_id); // Deserialize arguments and convert them into wasmi types. - let args = Vec::::decode(&mut &args[..]) + let args = Vec::::decode(&mut args) .map_err(|_| "Can't decode serialized arguments for the invocation")? .into_iter() .map(Into::into) diff --git a/client/executor/wasmtime/src/tests.rs b/client/executor/wasmtime/src/tests.rs index c1e626f12d1aa..08807f1dec414 100644 --- a/client/executor/wasmtime/src/tests.rs +++ b/client/executor/wasmtime/src/tests.rs @@ -313,7 +313,7 @@ fn test_max_memory_pages() { #[test] fn test_instances_without_reuse_are_not_leaked() { let runtime = crate::create_runtime::( - RuntimeBlob::uncompress_if_needed(&wasm_binary_unwrap()[..]).unwrap(), + RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(), crate::Config { heap_pages: 2048, max_memory_size: None, diff --git a/client/finality-grandpa/src/communication/gossip.rs b/client/finality-grandpa/src/communication/gossip.rs index 51d832c3b27be..4e8e047a9b640 100644 --- a/client/finality-grandpa/src/communication/gossip.rs +++ b/client/finality-grandpa/src/communication/gossip.rs @@ -615,8 +615,7 @@ impl Peers { // `LUCKY_PEERS / 2` is filled we start allocating to the second stage set. let half_lucky = LUCKY_PEERS / 2; let one_and_a_half_lucky = LUCKY_PEERS + half_lucky; - let mut n_authorities_added = 0; - for peer_id in shuffled_authorities { + for (n_authorities_added, peer_id) in shuffled_authorities.enumerate() { if n_authorities_added < half_lucky { first_stage_peers.insert(*peer_id); } else if n_authorities_added < one_and_a_half_lucky { @@ -624,8 +623,6 @@ impl Peers { } else { break } - - n_authorities_added += 1; } // fill up first and second sets with remaining peers (either full or authorities) diff --git a/client/finality-grandpa/src/lib.rs b/client/finality-grandpa/src/lib.rs index b8873d00efa7c..af85965c53c10 100644 --- a/client/finality-grandpa/src/lib.rs +++ b/client/finality-grandpa/src/lib.rs @@ -267,7 +267,7 @@ pub struct Config { impl Config { fn name(&self) -> &str { - self.name.as_ref().map(|s| s.as_str()).unwrap_or("") + self.name.as_deref().unwrap_or("") } } diff --git a/client/rpc/src/state/state_full.rs b/client/rpc/src/state/state_full.rs index 2c5a985a2b016..b8132094fe8d6 100644 --- a/client/rpc/src/state/state_full.rs +++ b/client/rpc/src/state/state_full.rs @@ -441,10 +441,7 @@ where keys: Option>, ) { let keys = Into::>>::into(keys); - let stream = match self - .client - .storage_changes_notification_stream(keys.as_ref().map(|x| &**x), None) - { + let stream = match self.client.storage_changes_notification_stream(keys.as_deref(), None) { Ok(stream) => stream, Err(err) => { let _ = subscriber.reject(client_err(err).into()); diff --git a/client/rpc/src/state/tests.rs b/client/rpc/src/state/tests.rs index d3aca181a41e8..9dbe02cdb7d64 100644 --- a/client/rpc/src/state/tests.rs +++ b/client/rpc/src/state/tests.rs @@ -32,7 +32,7 @@ use substrate_test_runtime_client::{prelude::*, runtime}; const STORAGE_KEY: &[u8] = b"child"; fn prefixed_storage_key() -> PrefixedStorageKey { - let child_info = ChildInfo::new_default(&STORAGE_KEY[..]); + let child_info = ChildInfo::new_default(STORAGE_KEY); child_info.prefixed_storage_key() } diff --git a/client/rpc/src/system/tests.rs b/client/rpc/src/system/tests.rs index 3e5241e2638b2..5d6945b714200 100644 --- a/client/rpc/src/system/tests.rs +++ b/client/rpc/src/system/tests.rs @@ -354,26 +354,26 @@ fn test_add_reset_log_filter() { }; // Initiate logs loop in child process - child_in.write(b"\n").unwrap(); + child_in.write_all(b"\n").unwrap(); assert!(read_line().contains(EXPECTED_BEFORE_ADD)); // Initiate add directive & reload in child process - child_in.write(b"add_reload\n").unwrap(); + child_in.write_all(b"add_reload\n").unwrap(); assert!(read_line().contains(EXPECTED_BEFORE_ADD)); assert!(read_line().contains(EXPECTED_AFTER_ADD)); // Check that increasing the max log level works - child_in.write(b"add_trace\n").unwrap(); + child_in.write_all(b"add_trace\n").unwrap(); assert!(read_line().contains(EXPECTED_WITH_TRACE)); assert!(read_line().contains(EXPECTED_BEFORE_ADD)); assert!(read_line().contains(EXPECTED_AFTER_ADD)); // Initiate logs filter reset in child process - child_in.write(b"reset\n").unwrap(); + child_in.write_all(b"reset\n").unwrap(); assert!(read_line().contains(EXPECTED_BEFORE_ADD)); // Return from child process - child_in.write(b"exit\n").unwrap(); + child_in.write_all(b"exit\n").unwrap(); assert!(child_process.wait().expect("Error waiting for child process").success()); // Check for EOF diff --git a/client/service/src/builder.rs b/client/service/src/builder.rs index 262ba53a33d49..c713b4936c6b0 100644 --- a/client/service/src/builder.rs +++ b/client/service/src/builder.rs @@ -363,7 +363,7 @@ where spawn_handle, config.clone(), )?; - Ok(crate::client::Client::new( + crate::client::Client::new( backend, executor, genesis_storage, @@ -373,7 +373,7 @@ where prometheus_registry, telemetry, config, - )?) + ) } /// Parameters to pass into `build`. diff --git a/client/service/src/client/call_executor.rs b/client/service/src/client/call_executor.rs index 739ad029dc190..fedd3400488d2 100644 --- a/client/service/src/client/call_executor.rs +++ b/client/service/src/client/call_executor.rs @@ -266,9 +266,7 @@ where &runtime_code, self.spawn_handle.clone(), ) - .with_storage_transaction_cache( - storage_transaction_cache.as_mut().map(|c| &mut **c), - ) + .with_storage_transaction_cache(storage_transaction_cache.as_deref_mut()) .set_parent_hash(at_hash); state_machine.execute_using_consensus_failure_handler( execution_manager, diff --git a/client/service/src/client/client.rs b/client/service/src/client/client.rs index 452450c71e785..9d898c7d1eb8f 100644 --- a/client/service/src/client/client.rs +++ b/client/service/src/client/client.rs @@ -1409,10 +1409,9 @@ where id: &BlockId, key: &StorageKey, ) -> sp_blockchain::Result> { - Ok(self - .state_at(id)? + self.state_at(id)? .storage_hash(&key.0) - .map_err(|e| sp_blockchain::Error::from_state(Box::new(e)))?) + .map_err(|e| sp_blockchain::Error::from_state(Box::new(e))) } fn child_storage_keys( @@ -1449,10 +1448,9 @@ where child_info: &ChildInfo, key: &StorageKey, ) -> sp_blockchain::Result> { - Ok(self - .state_at(id)? + self.state_at(id)? .child_storage_hash(child_info, &key.0) - .map_err(|e| sp_blockchain::Error::from_state(Box::new(e)))?) + .map_err(|e| sp_blockchain::Error::from_state(Box::new(e))) } } diff --git a/client/state-db/src/noncanonical.rs b/client/state-db/src/noncanonical.rs index 0509e54946e92..d7c83492e563c 100644 --- a/client/state-db/src/noncanonical.rs +++ b/client/state-db/src/noncanonical.rs @@ -134,12 +134,12 @@ fn discard_descendants( hash: &BlockHash, ) -> u32 { let (first, mut remainder) = if let Some((first, rest)) = levels.0.split_first_mut() { - (Some(first), (rest, &mut levels.1[..])) + (Some(first), (rest, &mut *levels.1)) } else { if let Some((first, rest)) = levels.1.split_first_mut() { - (Some(first), (&mut levels.0[..], rest)) + (Some(first), (&mut *levels.0, rest)) } else { - (None, (&mut levels.0[..], &mut levels.1[..])) + (None, (&mut *levels.0, &mut *levels.1)) } }; let mut pinned_children = 0; @@ -261,8 +261,7 @@ impl NonCanonicalOverlay { .push((to_meta_key(LAST_CANONICAL, &()), last_canonicalized.encode())); self.last_canonicalized = Some(last_canonicalized); } else if self.last_canonicalized.is_some() { - if number < front_block_number || - number >= front_block_number + self.levels.len() as u64 + 1 + if number < front_block_number || number > front_block_number + self.levels.len() as u64 { trace!(target: "state-db", "Failed to insert block {}, current is {} .. {})", number, diff --git a/client/tracing/proc-macro/src/lib.rs b/client/tracing/proc-macro/src/lib.rs index b1ffcb97b752e..ba757619fb5a0 100644 --- a/client/tracing/proc-macro/src/lib.rs +++ b/client/tracing/proc-macro/src/lib.rs @@ -119,7 +119,7 @@ pub fn prefix_logs_with(arg: TokenStream, item: TokenStream) -> TokenStream { let name = syn::parse_macro_input!(arg as Expr); let crate_name = match crate_name("sc-tracing") { - Ok(FoundCrate::Itself) => Ident::from(Ident::new("sc_tracing", Span::call_site())), + Ok(FoundCrate::Itself) => Ident::new("sc_tracing", Span::call_site()), Ok(FoundCrate::Name(crate_name)) => Ident::new(&crate_name, Span::call_site()), Err(e) => return Error::new(Span::call_site(), e).to_compile_error().into(), }; diff --git a/client/tracing/src/block/mod.rs b/client/tracing/src/block/mod.rs index 8280d4613a189..067cdafa0ae30 100644 --- a/client/tracing/src/block/mod.rs +++ b/client/tracing/src/block/mod.rs @@ -267,7 +267,7 @@ where .lock() .drain() // Patch wasm identifiers - .filter_map(|(_, s)| patch_and_filter(SpanDatum::from(s), targets)) + .filter_map(|(_, s)| patch_and_filter(s, targets)) .collect(); let events: Vec<_> = block_subscriber .events @@ -315,7 +315,7 @@ fn event_values_filter(event: &TraceEvent, filter_kind: &str, values: &str) -> b .values .string_values .get(filter_kind) - .and_then(|value| Some(check_target(values, value, &event.level))) + .map(|value| check_target(values, value, &event.level)) .unwrap_or(false) } diff --git a/client/tracing/src/lib.rs b/client/tracing/src/lib.rs index cbbd8063c34fa..ff3723e0d1a9a 100644 --- a/client/tracing/src/lib.rs +++ b/client/tracing/src/lib.rs @@ -464,7 +464,10 @@ impl From for sp_rpc::tracing::Span { mod tests { use super::*; use parking_lot::Mutex; - use std::sync::Arc; + use std::sync::{ + mpsc::{Receiver, Sender}, + Arc, + }; use tracing_subscriber::layer::SubscriberExt; struct TestTraceHandler { @@ -617,14 +620,14 @@ mod tests { let span1 = tracing::info_span!(target: "test_target", "test_span1"); let _guard1 = span1.enter(); - let (tx, rx) = mpsc::channel(); + let (tx, rx): (Sender, Receiver) = mpsc::channel(); let handle = thread::spawn(move || { let span2 = tracing::info_span!(target: "test_target", "test_span2"); let _guard2 = span2.enter(); // emit event tracing::event!(target: "test_target", tracing::Level::INFO, "test_event1"); for msg in rx.recv() { - if msg == false { + if !msg { break } } diff --git a/client/transaction-pool/src/graph/pool.rs b/client/transaction-pool/src/graph/pool.rs index 909ea559f5527..39be43f82c8b9 100644 --- a/client/transaction-pool/src/graph/pool.rs +++ b/client/transaction-pool/src/graph/pool.rs @@ -224,12 +224,8 @@ impl Pool { hashes: &[ExtrinsicHash], ) -> Result<(), B::Error> { // Get details of all extrinsics that are already in the pool - let in_pool_tags = self - .validated_pool - .extrinsics_tags(hashes) - .into_iter() - .filter_map(|x| x) - .flatten(); + let in_pool_tags = + self.validated_pool.extrinsics_tags(hashes).into_iter().flatten().flatten(); // Prune all transactions that provide given tags let prune_status = self.validated_pool.prune_tags(in_pool_tags)?; diff --git a/frame/authority-discovery/src/lib.rs b/frame/authority-discovery/src/lib.rs index d5f0a4c1d3392..03f6e753fd475 100644 --- a/frame/authority-discovery/src/lib.rs +++ b/frame/authority-discovery/src/lib.rs @@ -61,17 +61,12 @@ pub mod pallet { pub(super) type NextKeys = StorageValue<_, WeakBoundedVec, ValueQuery>; + #[cfg_attr(feature = "std", derive(Default))] #[pallet::genesis_config] pub struct GenesisConfig { pub keys: Vec, } - #[cfg(feature = "std")] - impl Default for GenesisConfig { - fn default() -> Self { - Self { keys: Default::default() } - } - } #[pallet::genesis_build] impl GenesisBuild for GenesisConfig { fn build(&self) { diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index 6f825e4e7dff9..db453fc57e9e6 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -479,9 +479,9 @@ mod tests { where I: 'a + IntoIterator, { - for (id, data) in digests { + for (id, mut data) in digests { if id == TEST_ID { - return u64::decode(&mut &data[..]).ok() + return u64::decode(&mut data).ok() } } @@ -499,9 +499,9 @@ mod tests { let author = AuthorGiven::find_author(pre_runtime_digests).ok_or_else(|| "no author")?; - for (id, seal) in seals { + for (id, mut seal) in seals { if id == TEST_ID { - match u64::decode(&mut &seal[..]) { + match u64::decode(&mut seal) { Err(_) => return Err("wrong seal"), Ok(a) => { if a != author { diff --git a/frame/babe/src/lib.rs b/frame/babe/src/lib.rs index 424f2df5c16d0..e2cc36ca098fe 100644 --- a/frame/babe/src/lib.rs +++ b/frame/babe/src/lib.rs @@ -310,19 +310,13 @@ pub mod pallet { #[pallet::storage] pub(super) type NextEpochConfig = StorageValue<_, BabeEpochConfiguration>; + #[cfg_attr(feature = "std", derive(Default))] #[pallet::genesis_config] pub struct GenesisConfig { pub authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, pub epoch_config: Option, } - #[cfg(feature = "std")] - impl Default for GenesisConfig { - fn default() -> Self { - GenesisConfig { authorities: Default::default(), epoch_config: Default::default() } - } - } - #[pallet::genesis_build] impl GenesisBuild for GenesisConfig { fn build(&self) { diff --git a/frame/bags-list/src/list/mod.rs b/frame/bags-list/src/list/mod.rs index 17844b51d4d5a..aba31b67b2863 100644 --- a/frame/bags-list/src/list/mod.rs +++ b/frame/bags-list/src/list/mod.rs @@ -742,7 +742,7 @@ impl Bag { /// Check if the bag contains a node with `id`. #[cfg(feature = "std")] fn contains(&self, id: &T::AccountId) -> bool { - self.iter().find(|n| n.id() == id).is_some() + self.iter().any(|n| n.id() == id) } } diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index a774cfd61edf5..86e3f2ec05984 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -409,12 +409,7 @@ pub mod pallet { let reducible_balance = Self::reducible_balance(&transactor, keep_alive); let dest = T::Lookup::lookup(dest)?; let keep_alive = if keep_alive { KeepAlive } else { AllowDeath }; - >::transfer( - &transactor, - &dest, - reducible_balance, - keep_alive.into(), - )?; + >::transfer(&transactor, &dest, reducible_balance, keep_alive)?; Ok(()) } @@ -619,7 +614,7 @@ pub enum Reasons { impl From for Reasons { fn from(r: WithdrawReasons) -> Reasons { - if r == WithdrawReasons::from(WithdrawReasons::TRANSACTION_PAYMENT) { + if r == WithdrawReasons::TRANSACTION_PAYMENT { Reasons::Fee } else if r.contains(WithdrawReasons::TRANSACTION_PAYMENT) { Reasons::All diff --git a/frame/contracts/src/storage/meter.rs b/frame/contracts/src/storage/meter.rs index 2dbd7ede615d2..28dc3356f7143 100644 --- a/frame/contracts/src/storage/meter.rs +++ b/frame/contracts/src/storage/meter.rs @@ -592,8 +592,7 @@ mod tests { contract: BOB, amount: Deposit::Charge(::Currency::minimum_balance() * 2), terminated: false, - }], - ..Default::default() + }] } ) }); @@ -663,8 +662,7 @@ mod tests { amount: Deposit::Charge(2), terminated: false } - ], - ..Default::default() + ] } ) }); @@ -717,8 +715,7 @@ mod tests { amount: Deposit::Charge(12), terminated: false } - ], - ..Default::default() + ] } ) }); diff --git a/frame/contracts/src/wasm/runtime.rs b/frame/contracts/src/wasm/runtime.rs index cae68208b31eb..7c9e19f6ef78a 100644 --- a/frame/contracts/src/wasm/runtime.rs +++ b/frame/contracts/src/wasm/runtime.rs @@ -1592,7 +1592,7 @@ define_env!(Env, , output_len_ptr: u32 ) -> u32 => { use crate::chain_extension::{ChainExtension, Environment, RetVal}; - if ::ChainExtension::enabled() == false { + if !::ChainExtension::enabled() { Err(Error::::NoChainExtension)?; } let env = Environment::new(ctx, input_ptr, input_len, output_ptr, output_len_ptr); diff --git a/frame/election-provider-multi-phase/src/unsigned.rs b/frame/election-provider-multi-phase/src/unsigned.rs index 6ce0ddfe67644..da56dd4d073df 100644 --- a/frame/election-provider-multi-phase/src/unsigned.rs +++ b/frame/election-provider-multi-phase/src/unsigned.rs @@ -544,7 +544,7 @@ impl Pallet { // Time to finish. We might have reduced less than expected due to rounding error. Increase // one last time if we have any room left, the reduce until we are sure we are below limit. - while voters + 1 <= max_voters && weight_with(voters + 1) < max_weight { + while voters < max_voters && weight_with(voters + 1) < max_weight { voters += 1; } while voters.checked_sub(1).is_some() && weight_with(voters) > max_weight { diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 06474cd37bbdf..b0e0a6fb984e8 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -836,7 +836,7 @@ impl Pallet { /// Check if `who` is currently an active runner-up. fn is_runner_up(who: &T::AccountId) -> bool { - Self::runners_up().iter().position(|r| &r.who == who).is_some() + Self::runners_up().iter().any(|r| &r.who == who) } /// Get the members' account ids. diff --git a/frame/examples/basic/src/lib.rs b/frame/examples/basic/src/lib.rs index 13c4591be28fd..56e8db6936249 100644 --- a/frame/examples/basic/src/lib.rs +++ b/frame/examples/basic/src/lib.rs @@ -738,7 +738,7 @@ where info: &DispatchInfoOf, len: usize, ) -> Result { - Ok(self.validate(who, call, info, len).map(|_| ())?) + self.validate(who, call, info, len).map(|_| ()) } fn validate( diff --git a/frame/grandpa/src/lib.rs b/frame/grandpa/src/lib.rs index 560c933f108c1..1f6139cf81fdc 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -327,18 +327,12 @@ pub mod pallet { #[pallet::getter(fn session_for_set)] pub(super) type SetIdSession = StorageMap<_, Twox64Concat, SetId, SessionIndex>; + #[cfg_attr(feature = "std", derive(Default))] #[pallet::genesis_config] pub struct GenesisConfig { pub authorities: AuthorityList, } - #[cfg(feature = "std")] - impl Default for GenesisConfig { - fn default() -> Self { - Self { authorities: Default::default() } - } - } - #[pallet::genesis_build] impl GenesisBuild for GenesisConfig { fn build(&self) { diff --git a/frame/im-online/src/tests.rs b/frame/im-online/src/tests.rs index cab5df9ebe541..288081556a085 100644 --- a/frame/im-online/src/tests.rs +++ b/frame/im-online/src/tests.rs @@ -341,7 +341,7 @@ fn should_not_send_a_report_if_already_online() { UintAuthorityId::set_all_keys(vec![1, 2, 3]); // we expect error, since the authority is already online. let mut res = ImOnline::send_heartbeats(4).unwrap(); - assert_eq!(res.next().unwrap().unwrap(), ()); + res.next().unwrap().unwrap(); assert_eq!(res.next().unwrap().unwrap_err(), OffchainErr::AlreadyOnline(1)); assert_eq!(res.next().unwrap().unwrap_err(), OffchainErr::AlreadyOnline(2)); assert_eq!(res.next(), None); diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index e349d7a1cc9a5..4fef5385eb2c5 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -153,7 +153,6 @@ pub fn new_test_ext() -> sp_io::TestExternalities { pallet_scored_pool::GenesisConfig:: { pool: vec![(5, None), (10, Some(1)), (20, Some(2)), (31, Some(2)), (40, Some(3))], member_count: 2, - ..Default::default() } .assimilate_storage(&mut t) .unwrap(); diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index cae9a6159b162..7a0783718705a 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -480,11 +480,11 @@ pub mod pallet { let queued_keys: Vec<_> = initial_validators_1 .iter() .cloned() - .filter_map(|v| { - Some(( + .map(|v| { + ( v.clone(), Pallet::::load_keys(&v).expect("Validator in session 1 missing keys!"), - )) + ) }) .collect(); diff --git a/frame/society/src/lib.rs b/frame/society/src/lib.rs index abc90d5186f29..3d2814ad5232b 100644 --- a/frame/society/src/lib.rs +++ b/frame/society/src/lib.rs @@ -1290,7 +1290,7 @@ fn pick_item<'a, R: RngCore, T>(rng: &mut R, items: &'a [T]) -> Option<&'a T> { } /// Pick a new PRN, in the range [0, `max`] (inclusive). -fn pick_usize<'a, R: RngCore>(rng: &mut R, max: usize) -> usize { +fn pick_usize(rng: &mut R, max: usize) -> usize { (rng.next_u32() % (max as u32 + 1)) as usize } @@ -1316,9 +1316,9 @@ impl, I: 'static> Pallet { // Skip ahead to the suggested position .skip(pos) // Keep skipping ahead until the position changes - .skip_while(|(_, x)| x.value <= bids[pos].value) // Get the element when things changed - .next(); + .find(|(_, x)| x.value > bids[pos].value); + // If the element is not at the end of the list, insert the new element // in the spot. if let Some((p, _)) = different_bid { @@ -1351,7 +1351,7 @@ impl, I: 'static> Pallet { /// Check a user is a bid. fn is_bid(bids: &Vec>>, who: &T::AccountId) -> bool { // Bids are ordered by `value`, so we cannot binary search for a user. - bids.iter().find(|bid| bid.who == *who).is_some() + bids.iter().any(|bid| bid.who == *who) } /// Check a user is a candidate. diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index f6e0526917540..268618fb5f44f 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -412,7 +412,7 @@ impl Default for RewardDestination { } /// Preference of what happens regarding validation. -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)] +#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, Default)] pub struct ValidatorPrefs { /// Reward that validator takes up-front; only the rest is split between themselves and /// nominators. @@ -424,12 +424,6 @@ pub struct ValidatorPrefs { pub blocked: bool, } -impl Default for ValidatorPrefs { - fn default() -> Self { - ValidatorPrefs { commission: Default::default(), blocked: false } - } -} - /// Just a Balance/BlockNumber tuple to encode when a chunk of funds will be unlocked. #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)] pub struct UnlockChunk { diff --git a/frame/staking/src/pallet/impls.rs b/frame/staking/src/pallet/impls.rs index dcbba63632051..ea2c746ed7177 100644 --- a/frame/staking/src/pallet/impls.rs +++ b/frame/staking/src/pallet/impls.rs @@ -224,7 +224,7 @@ impl Pallet { let dest = Self::payee(stash); match dest { RewardDestination::Controller => Self::bonded(stash) - .and_then(|controller| Some(T::Currency::deposit_creating(&controller, amount))), + .map(|controller| T::Currency::deposit_creating(&controller, amount)), RewardDestination::Stash => T::Currency::deposit_into_existing(stash, amount).ok(), RewardDestination::Staked => Self::bonded(stash) .and_then(|c| Self::ledger(&c).map(|l| (c, l))) @@ -1160,7 +1160,7 @@ where add_db_reads_writes(1, 0); // Reverse because it's more likely to find reports from recent eras. - match eras.iter().rev().filter(|&&(_, ref sesh)| sesh <= &slash_session).next() { + match eras.iter().rev().find(|&&(_, ref sesh)| sesh <= &slash_session) { Some(&(ref slash_era, _)) => *slash_era, // Before bonding period. defensive - should be filtered out. None => return consumed_weight, diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index 7990245068f9c..8d465c8c93dc4 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -2262,7 +2262,7 @@ fn slash_in_old_span_does_not_deselect() { ); // the validator doesn't get chilled again - assert!(::Validators::iter().find(|(stash, _)| *stash == 11).is_some()); + assert!(::Validators::iter().any(|(stash, _)| stash == 11)); // but we are still forcing a new era assert_eq!(Staking::force_era(), Forcing::ForceNew); @@ -2279,7 +2279,7 @@ fn slash_in_old_span_does_not_deselect() { ); // the validator doesn't get chilled again - assert!(::Validators::iter().find(|(stash, _)| *stash == 11).is_some()); + assert!(::Validators::iter().any(|(stash, _)| stash == 11)); // but it's disabled assert!(is_disabled(10)); @@ -4003,8 +4003,7 @@ mod election_data_provider { assert!(>::iter().map(|(x, _)| x).all(|v| Staking::voters(None) .unwrap() .into_iter() - .find(|(w, _, t)| { v == *w && t[0] == *w }) - .is_some())) + .any(|(w, _, t)| { v == w && t[0] == w }))) }) } diff --git a/frame/support/procedural/src/pallet/parse/storage.rs b/frame/support/procedural/src/pallet/parse/storage.rs index ca48c568e158a..effe0ce6c55d8 100644 --- a/frame/support/procedural/src/pallet/parse/storage.rs +++ b/frame/support/procedural/src/pallet/parse/storage.rs @@ -704,11 +704,11 @@ impl StorageDef { }) .unwrap_or(Some(QueryKind::OptionQuery)); // This value must match the default generic. - if query_kind.is_none() && getter.is_some() { + if let (None, Some(getter)) = (query_kind.as_ref(), getter.as_ref()) { let msg = "Invalid pallet::storage, cannot generate getter because QueryKind is not \ identifiable. QueryKind must be `OptionQuery`, `ValueQuery`, or default one to be \ identifiable."; - return Err(syn::Error::new(getter.unwrap().span(), msg)) + return Err(syn::Error::new(getter.span(), msg)) } Ok(StorageDef { diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 765fb5d9d7c35..b5f4ab97767c2 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -1546,7 +1546,7 @@ macro_rules! decl_module { ::current_storage_version(), ); - (|| { $( $impl )* })() + { $( $impl )* } } #[cfg(feature = "try-runtime")] diff --git a/frame/support/src/storage/migration.rs b/frame/support/src/storage/migration.rs index b2339efd0d204..713c2b0f3fe01 100644 --- a/frame/support/src/storage/migration.rs +++ b/frame/support/src/storage/migration.rs @@ -181,8 +181,8 @@ pub fn storage_iter_with_suffix( prefix.extend_from_slice(&storage_prefix); prefix.extend_from_slice(suffix); let previous_key = prefix.clone(); - let closure = |raw_key_without_prefix: &[u8], raw_value: &[u8]| { - let value = T::decode(&mut &raw_value[..])?; + let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| { + let value = T::decode(&mut raw_value)?; Ok((raw_key_without_prefix.to_vec(), value)) }; @@ -213,10 +213,10 @@ pub fn storage_key_iter_with_suffix< prefix.extend_from_slice(&storage_prefix); prefix.extend_from_slice(suffix); let previous_key = prefix.clone(); - let closure = |raw_key_without_prefix: &[u8], raw_value: &[u8]| { + let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| { let mut key_material = H::reverse(raw_key_without_prefix); let key = K::decode(&mut key_material)?; - let value = T::decode(&mut &raw_value[..])?; + let value = T::decode(&mut raw_value)?; Ok((key, value)) }; PrefixIterator { prefix, previous_key, drain: false, closure, phantom: Default::default() } diff --git a/frame/support/src/storage/mod.rs b/frame/support/src/storage/mod.rs index d79ddf09b7cc7..04876895dc490 100644 --- a/frame/support/src/storage/mod.rs +++ b/frame/support/src/storage/mod.rs @@ -1018,8 +1018,8 @@ impl ChildTriePrefixIterator<(Vec, T)> { pub fn with_prefix(child_info: &ChildInfo, prefix: &[u8]) -> Self { let prefix = prefix.to_vec(); let previous_key = prefix.clone(); - let closure = |raw_key_without_prefix: &[u8], raw_value: &[u8]| { - let value = T::decode(&mut &raw_value[..])?; + let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| { + let value = T::decode(&mut raw_value)?; Ok((raw_key_without_prefix.to_vec(), value)) }; @@ -1045,10 +1045,10 @@ impl ChildTriePrefixIterator<(K, T)> { ) -> Self { let prefix = prefix.to_vec(); let previous_key = prefix.clone(); - let closure = |raw_key_without_prefix: &[u8], raw_value: &[u8]| { + let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| { let mut key_material = H::reverse(raw_key_without_prefix); let key = K::decode(&mut key_material)?; - let value = T::decode(&mut &raw_value[..])?; + let value = T::decode(&mut raw_value)?; Ok((key, value)) }; diff --git a/frame/support/test/pallet/src/lib.rs b/frame/support/test/pallet/src/lib.rs index bd181ea5b81bf..25741313c2a03 100644 --- a/frame/support/test/pallet/src/lib.rs +++ b/frame/support/test/pallet/src/lib.rs @@ -30,15 +30,9 @@ pub mod pallet { pub trait Config: frame_system::Config {} #[pallet::genesis_config] + #[cfg_attr(feature = "std", derive(Default))] pub struct GenesisConfig {} - #[cfg(feature = "std")] - impl Default for GenesisConfig { - fn default() -> Self { - Self {} - } - } - #[pallet::genesis_build] impl GenesisBuild for GenesisConfig { fn build(&self) {} diff --git a/frame/support/test/tests/genesisconfig.rs b/frame/support/test/tests/genesisconfig.rs index 7895e863fd826..367c7236d0158 100644 --- a/frame/support/test/tests/genesisconfig.rs +++ b/frame/support/test/tests/genesisconfig.rs @@ -40,5 +40,5 @@ impl Config for Test {} #[test] fn init_genesis_config() { - GenesisConfig:: { t: Default::default() }; + GenesisConfig::::default(); } diff --git a/frame/support/test/tests/issue2219.rs b/frame/support/test/tests/issue2219.rs index 196068ac2fa4a..d7e3d2cb5b135 100644 --- a/frame/support/test/tests/issue2219.rs +++ b/frame/support/test/tests/issue2219.rs @@ -184,7 +184,9 @@ frame_support::construct_runtime!( #[test] fn create_genesis_config() { - GenesisConfig { + let config = GenesisConfig { module: module::GenesisConfig { request_life_time: 0, enable_storage_role: true }, }; + assert_eq!(config.module.request_life_time, 0); + assert!(config.module.enable_storage_role); } diff --git a/frame/support/test/tests/pallet.rs b/frame/support/test/tests/pallet.rs index 1e923a6fdd6ec..59b581eda58e4 100644 --- a/frame/support/test/tests/pallet.rs +++ b/frame/support/test/tests/pallet.rs @@ -881,7 +881,7 @@ fn pallet_expand_deposit_event() { #[test] fn pallet_new_call_variant() { - Call::Example(pallet::Call::new_call_variant_foo(3, 4)); + pallet::Call::::new_call_variant_foo(3, 4); } #[test] diff --git a/frame/system/src/extensions/check_genesis.rs b/frame/system/src/extensions/check_genesis.rs index 4b52691a6d328..a0679b11487f6 100644 --- a/frame/system/src/extensions/check_genesis.rs +++ b/frame/system/src/extensions/check_genesis.rs @@ -70,6 +70,6 @@ impl SignedExtension for CheckGenesis { info: &DispatchInfoOf, len: usize, ) -> Result { - Ok(self.validate(who, call, info, len).map(|_| ())?) + self.validate(who, call, info, len).map(|_| ()) } } diff --git a/frame/system/src/extensions/check_mortality.rs b/frame/system/src/extensions/check_mortality.rs index ed11c37598362..2fb99c9f45e2b 100644 --- a/frame/system/src/extensions/check_mortality.rs +++ b/frame/system/src/extensions/check_mortality.rs @@ -93,7 +93,7 @@ impl SignedExtension for CheckMortality { info: &DispatchInfoOf, len: usize, ) -> Result { - Ok(self.validate(who, call, info, len).map(|_| ())?) + self.validate(who, call, info, len).map(|_| ()) } } diff --git a/frame/system/src/extensions/check_non_zero_sender.rs b/frame/system/src/extensions/check_non_zero_sender.rs index 5910a865a7766..f517201fbebc2 100644 --- a/frame/system/src/extensions/check_non_zero_sender.rs +++ b/frame/system/src/extensions/check_non_zero_sender.rs @@ -72,7 +72,7 @@ where info: &DispatchInfoOf, len: usize, ) -> Result { - Ok(self.validate(who, call, info, len).map(|_| ())?) + self.validate(who, call, info, len).map(|_| ()) } fn validate( diff --git a/frame/system/src/extensions/check_spec_version.rs b/frame/system/src/extensions/check_spec_version.rs index dce70a940765a..0280d31f657ae 100644 --- a/frame/system/src/extensions/check_spec_version.rs +++ b/frame/system/src/extensions/check_spec_version.rs @@ -70,6 +70,6 @@ impl SignedExtension for CheckSpecVersion { info: &DispatchInfoOf, len: usize, ) -> Result { - Ok(self.validate(who, call, info, len).map(|_| ())?) + self.validate(who, call, info, len).map(|_| ()) } } diff --git a/frame/system/src/extensions/check_tx_version.rs b/frame/system/src/extensions/check_tx_version.rs index 69060729cccc3..b92d8978bde01 100644 --- a/frame/system/src/extensions/check_tx_version.rs +++ b/frame/system/src/extensions/check_tx_version.rs @@ -69,6 +69,6 @@ impl SignedExtension for CheckTxVersion { info: &DispatchInfoOf, len: usize, ) -> Result { - Ok(self.validate(who, call, info, len).map(|_| ())?) + self.validate(who, call, info, len).map(|_| ()) } } diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index 80d2934914691..cec45a8aa1cb1 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -637,19 +637,13 @@ pub mod pallet { #[pallet::storage] pub(super) type ExecutionPhase = StorageValue<_, Phase>; + #[cfg_attr(feature = "std", derive(Default))] #[pallet::genesis_config] pub struct GenesisConfig { #[serde(with = "sp_core::bytes")] pub code: Vec, } - #[cfg(feature = "std")] - impl Default for GenesisConfig { - fn default() -> Self { - Self { code: Default::default() } - } - } - #[pallet::genesis_build] impl GenesisBuild for GenesisConfig { fn build(&self) { diff --git a/frame/uniques/src/tests.rs b/frame/uniques/src/tests.rs index 0e0dc413a01a3..293140d5eda1a 100644 --- a/frame/uniques/src/tests.rs +++ b/frame/uniques/src/tests.rs @@ -39,7 +39,7 @@ fn assets() -> Vec<(u64, u32, u32)> { Some(Some(item)) } }) - .filter_map(|item| item) + .flatten() { let details = Class::::get(class).unwrap(); let instances = Asset::::iter_prefix(class).count() as u32; diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index fcad0c57f937d..c823bccf38b1b 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -572,14 +572,13 @@ impl Pallet { let mut total_locked_now: BalanceOf = Zero::zero(); let filtered_schedules = action .pick_schedules::(schedules) - .filter_map(|schedule| { + .filter(|schedule| { let locked_now = schedule.locked_at::(now); - if locked_now.is_zero() { - None - } else { + let keep = !locked_now.is_zero(); + if keep { total_locked_now = total_locked_now.saturating_add(locked_now); - Some(schedule) } + keep }) .collect::>(); diff --git a/primitives/api/proc-macro/src/decl_runtime_apis.rs b/primitives/api/proc-macro/src/decl_runtime_apis.rs index 6c6b8f453a267..8d90b09d0e8c0 100644 --- a/primitives/api/proc-macro/src/decl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/decl_runtime_apis.rs @@ -235,9 +235,7 @@ fn generate_native_call_generators(decl: &ItemTrait) -> Result { // compatible. To ensure that we forward it by ref/value, we use the value given by the // the user. Otherwise if it is not using the block, we don't need to add anything. let input_borrows = - params - .iter() - .map(|v| if type_is_using_block(&v.1) { v.2.clone() } else { None }); + params.iter().map(|v| if type_is_using_block(&v.1) { v.2 } else { None }); // Replace all `Block` with `NodeBlock`, add `'a` lifetime to references and collect // all the function inputs. @@ -380,7 +378,6 @@ fn generate_call_api_at_calls(decl: &ItemTrait) -> Result { // Generate the generator function result.push(quote!( #[cfg(any(feature = "std", test))] - #[allow(clippy::too_many_arguments)] pub fn #fn_name< R: #crate_::Encode + #crate_::Decode + PartialEq, NC: FnOnce() -> std::result::Result + std::panic::UnwindSafe, diff --git a/primitives/authorship/src/lib.rs b/primitives/authorship/src/lib.rs index 25eaeaf9bc16d..7ea19d9ea5ff5 100644 --- a/primitives/authorship/src/lib.rs +++ b/primitives/authorship/src/lib.rs @@ -88,13 +88,13 @@ impl sp_inherents::InherentDataProvider for InherentDataProvider async fn try_handle_error( &self, identifier: &InherentIdentifier, - error: &[u8], + mut error: &[u8], ) -> Option> { if *identifier != INHERENT_IDENTIFIER { return None } - let error = InherentError::decode(&mut &error[..]).ok()?; + let error = InherentError::decode(&mut error).ok()?; Some(Err(Error::Application(Box::from(format!("{:?}", error))))) } diff --git a/primitives/debug-derive/src/impls.rs b/primitives/debug-derive/src/impls.rs index bab0146e46824..060997fe97821 100644 --- a/primitives/debug-derive/src/impls.rs +++ b/primitives/debug-derive/src/impls.rs @@ -101,7 +101,7 @@ mod implementation { } } - fn derive_fields<'a>(name_str: &str, fields: Fields) -> TokenStream { + fn derive_fields(name_str: &str, fields: Fields) -> TokenStream { match fields { Fields::Named { names, this } => { let names_str: Vec<_> = names.iter().map(|x| x.to_string()).collect(); diff --git a/primitives/keystore/src/testing.rs b/primitives/keystore/src/testing.rs index eb5847207daaf..2723b743c10db 100644 --- a/primitives/keystore/src/testing.rs +++ b/primitives/keystore/src/testing.rs @@ -482,9 +482,7 @@ mod tests { assert!(res.is_none()); // insert key, sign again - let res = - SyncCryptoStore::insert_unknown(&store, ECDSA, suri, pair.public().as_ref()).unwrap(); - assert_eq!((), res); + SyncCryptoStore::insert_unknown(&store, ECDSA, suri, pair.public().as_ref()).unwrap(); let res = SyncCryptoStore::ecdsa_sign_prehashed(&store, ECDSA, &pair.public(), &msg).unwrap(); diff --git a/primitives/npos-elections/fuzzer/src/compact.rs b/primitives/npos-elections/fuzzer/src/compact.rs index 4e78c94b82572..595048575d99c 100644 --- a/primitives/npos-elections/fuzzer/src/compact.rs +++ b/primitives/npos-elections/fuzzer/src/compact.rs @@ -11,7 +11,7 @@ fn main() { loop { fuzz!(|fuzzer_data: &[u8]| { let result_decoded: Result = - ::decode(&mut &fuzzer_data[..]); + ::decode(&mut &*fuzzer_data); // Ignore errors as not every random sequence of bytes can be decoded as // InnerTestSolutionCompact if let Ok(decoded) = result_decoded { diff --git a/primitives/npos-elections/fuzzer/src/reduce.rs b/primitives/npos-elections/fuzzer/src/reduce.rs index 029bb18dc5b30..ad3f7dc260ef5 100644 --- a/primitives/npos-elections/fuzzer/src/reduce.rs +++ b/primitives/npos-elections/fuzzer/src/reduce.rs @@ -90,7 +90,7 @@ fn generate_random_phragmen_assignment( .map(|_| { let target = targets_to_chose_from.remove(rng.gen_range(0, targets_to_chose_from.len())); - if winners.iter().find(|w| **w == target).is_none() { + if winners.iter().all(|w| *w != target) { winners.push(target.clone()); } (target, rng.gen_range(1 * KSM, 100 * KSM)) diff --git a/primitives/npos-elections/src/reduce.rs b/primitives/npos-elections/src/reduce.rs index 057ee339bd7d3..f089a37e3fff3 100644 --- a/primitives/npos-elections/src/reduce.rs +++ b/primitives/npos-elections/src/reduce.rs @@ -275,9 +275,8 @@ fn reduce_4(assignments: &mut Vec>) -> u32 { }); // remove either one of them. - let who_removed = remove_indices.iter().find(|i| **i < 2usize).is_some(); - let other_removed = - remove_indices.into_iter().find(|i| *i >= 2usize).is_some(); + let who_removed = remove_indices.iter().any(|i| *i < 2usize); + let other_removed = remove_indices.into_iter().any(|i| i >= 2usize); match (who_removed, other_removed) { (false, true) => { diff --git a/primitives/runtime-interface/test/src/lib.rs b/primitives/runtime-interface/test/src/lib.rs index 785215b87421b..e76f54f69a808 100644 --- a/primitives/runtime-interface/test/src/lib.rs +++ b/primitives/runtime-interface/test/src/lib.rs @@ -62,17 +62,17 @@ fn call_wasm_method(binary: &[u8], method: &str) -> TestExte #[test] fn test_return_data() { - call_wasm_method::(&wasm_binary_unwrap()[..], "test_return_data"); + call_wasm_method::(wasm_binary_unwrap(), "test_return_data"); } #[test] fn test_return_option_data() { - call_wasm_method::(&wasm_binary_unwrap()[..], "test_return_option_data"); + call_wasm_method::(wasm_binary_unwrap(), "test_return_option_data"); } #[test] fn test_set_storage() { - let mut ext = call_wasm_method::(&wasm_binary_unwrap()[..], "test_set_storage"); + let mut ext = call_wasm_method::(wasm_binary_unwrap(), "test_set_storage"); let expected = "world"; assert_eq!(expected.as_bytes(), &ext.ext().storage("hello".as_bytes()).unwrap()[..]); @@ -81,30 +81,30 @@ fn test_set_storage() { #[test] fn test_return_value_into_mutable_reference() { call_wasm_method::( - &wasm_binary_unwrap()[..], + wasm_binary_unwrap(), "test_return_value_into_mutable_reference", ); } #[test] fn test_get_and_return_array() { - call_wasm_method::(&wasm_binary_unwrap()[..], "test_get_and_return_array"); + call_wasm_method::(wasm_binary_unwrap(), "test_get_and_return_array"); } #[test] fn test_array_as_mutable_reference() { - call_wasm_method::(&wasm_binary_unwrap()[..], "test_array_as_mutable_reference"); + call_wasm_method::(wasm_binary_unwrap(), "test_array_as_mutable_reference"); } #[test] fn test_return_input_public_key() { - call_wasm_method::(&wasm_binary_unwrap()[..], "test_return_input_public_key"); + call_wasm_method::(wasm_binary_unwrap(), "test_return_input_public_key"); } #[test] fn host_function_not_found() { - let err = call_wasm_method_with_result::<()>(&wasm_binary_unwrap()[..], "test_return_data") - .unwrap_err(); + let err = + call_wasm_method_with_result::<()>(wasm_binary_unwrap(), "test_return_data").unwrap_err(); assert!(err.contains("Instantiation: Export ")); assert!(err.contains(" not found")); @@ -114,7 +114,7 @@ fn host_function_not_found() { #[should_panic(expected = "Invalid utf8 data provided")] fn test_invalid_utf8_data_should_return_an_error() { call_wasm_method::( - &wasm_binary_unwrap()[..], + wasm_binary_unwrap(), "test_invalid_utf8_data_should_return_an_error", ); } @@ -122,7 +122,7 @@ fn test_invalid_utf8_data_should_return_an_error() { #[test] fn test_overwrite_native_function_implementation() { call_wasm_method::( - &wasm_binary_unwrap()[..], + wasm_binary_unwrap(), "test_overwrite_native_function_implementation", ); } @@ -130,7 +130,7 @@ fn test_overwrite_native_function_implementation() { #[test] fn test_u128_i128_as_parameter_and_return_value() { call_wasm_method::( - &wasm_binary_unwrap()[..], + wasm_binary_unwrap(), "test_u128_i128_as_parameter_and_return_value", ); } @@ -138,7 +138,7 @@ fn test_u128_i128_as_parameter_and_return_value() { #[test] fn test_vec_return_value_memory_is_freed() { call_wasm_method::( - &wasm_binary_unwrap()[..], + wasm_binary_unwrap(), "test_vec_return_value_memory_is_freed", ); } @@ -146,7 +146,7 @@ fn test_vec_return_value_memory_is_freed() { #[test] fn test_encoded_return_value_memory_is_freed() { call_wasm_method::( - &wasm_binary_unwrap()[..], + wasm_binary_unwrap(), "test_encoded_return_value_memory_is_freed", ); } @@ -154,7 +154,7 @@ fn test_encoded_return_value_memory_is_freed() { #[test] fn test_array_return_value_memory_is_freed() { call_wasm_method::( - &wasm_binary_unwrap()[..], + wasm_binary_unwrap(), "test_array_return_value_memory_is_freed", ); } @@ -162,14 +162,11 @@ fn test_array_return_value_memory_is_freed() { #[test] fn test_versionining_with_new_host_works() { // We call to the new wasm binary with new host function. - call_wasm_method::(&wasm_binary_unwrap()[..], "test_versionning_works"); + call_wasm_method::(wasm_binary_unwrap(), "test_versionning_works"); // we call to the old wasm binary with a new host functions // old versions of host functions should be called and test should be ok! - call_wasm_method::( - &wasm_binary_deprecated_unwrap()[..], - "test_versionning_works", - ); + call_wasm_method::(wasm_binary_deprecated_unwrap(), "test_versionning_works"); } #[test] @@ -224,7 +221,7 @@ fn test_tracing() { let _guard = tracing::subscriber::set_default(subscriber.clone()); // Call some method to generate a trace - call_wasm_method::(&wasm_binary_unwrap()[..], "test_return_data"); + call_wasm_method::(wasm_binary_unwrap(), "test_return_data"); let inner = subscriber.0.lock().unwrap(); assert!(inner.spans.contains("return_input_version_1")); @@ -232,5 +229,5 @@ fn test_tracing() { #[test] fn test_return_input_as_tuple() { - call_wasm_method::(&wasm_binary_unwrap()[..], "test_return_input_as_tuple"); + call_wasm_method::(wasm_binary_unwrap(), "test_return_input_as_tuple"); } diff --git a/primitives/runtime/src/generic/digest.rs b/primitives/runtime/src/generic/digest.rs index ca1daabb06d29..f3cb7b99efb61 100644 --- a/primitives/runtime/src/generic/digest.rs +++ b/primitives/runtime/src/generic/digest.rs @@ -33,19 +33,13 @@ use crate::{ use sp_core::RuntimeDebug; /// Generic header digest. -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)] +#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, Default)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize, parity_util_mem::MallocSizeOf))] pub struct Digest { /// A list of logs in the digest. pub logs: Vec, } -impl Default for Digest { - fn default() -> Self { - Self { logs: Vec::new() } - } -} - impl Digest { /// Get reference to all digest items. pub fn logs(&self) -> &[DigestItem] { diff --git a/primitives/runtime/src/generic/unchecked_extrinsic.rs b/primitives/runtime/src/generic/unchecked_extrinsic.rs index d919a67095d3a..d444d0352d5ae 100644 --- a/primitives/runtime/src/generic/unchecked_extrinsic.rs +++ b/primitives/runtime/src/generic/unchecked_extrinsic.rs @@ -395,7 +395,7 @@ mod tests { info: &DispatchInfoOf, len: usize, ) -> Result { - Ok(self.validate(who, call, info, len).map(|_| ())?) + self.validate(who, call, info, len).map(|_| ()) } } diff --git a/primitives/runtime/src/traits.rs b/primitives/runtime/src/traits.rs index 84c35597b4b1b..b2e218cb9db73 100644 --- a/primitives/runtime/src/traits.rs +++ b/primitives/runtime/src/traits.rs @@ -1074,7 +1074,7 @@ impl SignedExtension for () { info: &DispatchInfoOf, len: usize, ) -> Result { - Ok(self.validate(who, call, info, len).map(|_| ())?) + self.validate(who, call, info, len).map(|_| ()) } } diff --git a/primitives/state-machine/src/backend.rs b/primitives/state-machine/src/backend.rs index 215caaa17f302..8d0ac2d1369c9 100644 --- a/primitives/state-machine/src/backend.rs +++ b/primitives/state-machine/src/backend.rs @@ -208,7 +208,7 @@ pub trait Backend: sp_std::fmt::Debug { } let (root, parent_txs) = self.storage_root( delta - .map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..]))) + .map(|(k, v)| (k, v.as_ref().map(|v| &v[..]))) .chain(child_roots.iter().map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..])))), state_version, ); diff --git a/primitives/state-machine/src/ext.rs b/primitives/state-machine/src/ext.rs index 93e6ac6e5c530..e87b22d4f9b76 100644 --- a/primitives/state-machine/src/ext.rs +++ b/primitives/state-machine/src/ext.rs @@ -581,7 +581,7 @@ where target: "state", method = "ChildStorageRoot", ext_id = %HexDisplay::from(&self.id.to_le_bytes()), - child_info = %HexDisplay::from(&storage_key.as_ref()), + child_info = %HexDisplay::from(&storage_key), storage_root = %HexDisplay::from(&root.as_ref()), cached = false, ); @@ -599,7 +599,7 @@ where target: "state", method = "ChildStorageRoot", ext_id = %HexDisplay::from(&self.id.to_le_bytes()), - child_info = %HexDisplay::from(&storage_key.as_ref()), + child_info = %HexDisplay::from(&storage_key), storage_root = %HexDisplay::from(&root.as_ref()), cached = false, ); diff --git a/primitives/state-machine/src/testing.rs b/primitives/state-machine/src/testing.rs index e21644614c83c..6be601aa72b34 100644 --- a/primitives/state-machine/src/testing.rs +++ b/primitives/state-machine/src/testing.rs @@ -203,7 +203,7 @@ where /// /// This implementation will wipe the proof recorded in between calls. Consecutive calls will /// get their own proof from scratch. - pub fn execute_and_prove<'a, R>(&mut self, execute: impl FnOnce() -> R) -> (R, StorageProof) { + pub fn execute_and_prove(&mut self, execute: impl FnOnce() -> R) -> (R, StorageProof) { let proving_backend = InMemoryProvingBackend::new(&self.backend); let mut proving_ext = Ext::new( &mut self.overlay, diff --git a/primitives/timestamp/src/lib.rs b/primitives/timestamp/src/lib.rs index 9155cbd93b6c5..76725e28ac825 100644 --- a/primitives/timestamp/src/lib.rs +++ b/primitives/timestamp/src/lib.rs @@ -138,9 +138,9 @@ impl IsFatalError for InherentError { impl InherentError { /// Try to create an instance ouf of the given identifier and data. #[cfg(feature = "std")] - pub fn try_from(id: &InherentIdentifier, data: &[u8]) -> Option { + pub fn try_from(id: &InherentIdentifier, mut data: &[u8]) -> Option { if id == &INHERENT_IDENTIFIER { - ::decode(&mut &data[..]).ok() + ::decode(&mut data).ok() } else { None } @@ -227,7 +227,7 @@ impl sp_inherents::InherentDataProvider for InherentDataProvider { &self, inherent_data: &mut InherentData, ) -> Result<(), sp_inherents::Error> { - inherent_data.put_data(INHERENT_IDENTIFIER, &InherentType::from(self.timestamp)) + inherent_data.put_data(INHERENT_IDENTIFIER, &self.timestamp) } async fn try_handle_error( diff --git a/primitives/transaction-storage-proof/src/lib.rs b/primitives/transaction-storage-proof/src/lib.rs index bdfe16683ebc2..2e5aa3b2b9c71 100644 --- a/primitives/transaction-storage-proof/src/lib.rs +++ b/primitives/transaction-storage-proof/src/lib.rs @@ -67,7 +67,7 @@ pub trait TransactionStorageProofInherentData { impl TransactionStorageProofInherentData for InherentData { fn storage_proof(&self) -> Result, Error> { - Ok(self.get_data(&INHERENT_IDENTIFIER)?) + self.get_data(&INHERENT_IDENTIFIER) } } @@ -98,13 +98,13 @@ impl sp_inherents::InherentDataProvider for InherentDataProvider { async fn try_handle_error( &self, identifier: &InherentIdentifier, - error: &[u8], + mut error: &[u8], ) -> Option> { if *identifier != INHERENT_IDENTIFIER { return None } - let error = InherentError::decode(&mut &error[..]).ok()?; + let error = InherentError::decode(&mut error).ok()?; Some(Err(Error::Application(Box::from(format!("{:?}", error))))) } diff --git a/primitives/trie/src/lib.rs b/primitives/trie/src/lib.rs index ffaee2037d1c9..f598615be9098 100644 --- a/primitives/trie/src/lib.rs +++ b/primitives/trie/src/lib.rs @@ -281,7 +281,7 @@ where L: TrieConfiguration, DB: hash_db::HashDBRef, { - Ok(TrieDB::::new(&*db, root)?.get(key).map(|x| x.map(|val| val.to_vec()))?) + TrieDB::::new(&*db, root)?.get(key).map(|x| x.map(|val| val.to_vec())) } /// Read a value from the trie with given Query. @@ -296,9 +296,9 @@ where Q: Query, DB: hash_db::HashDBRef, { - Ok(TrieDB::::new(&*db, root)? + TrieDB::::new(&*db, root)? .get_with(key, query) - .map(|x| x.map(|val| val.to_vec()))?) + .map(|x| x.map(|val| val.to_vec())) } /// Determine the empty trie root. diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index c6112db2374e0..b03998621b31f 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -665,13 +665,7 @@ fn code_using_trie() -> u64 { if let Ok(trie) = TrieDB::::new(&mdb, &root) { if let Ok(iter) = trie.iter() { - let mut iter_pairs = Vec::new(); - for pair in iter { - if let Ok((key, value)) = pair { - iter_pairs.push((key, value.to_vec())); - } - } - iter_pairs.len() as u64 + iter.flatten().count() as u64 } else { 102 } diff --git a/utils/frame/benchmarking-cli/src/command.rs b/utils/frame/benchmarking-cli/src/command.rs index 94e1e0c8c1b88..bd103862fe2c3 100644 --- a/utils/frame/benchmarking-cli/src/command.rs +++ b/utils/frame/benchmarking-cli/src/command.rs @@ -176,9 +176,7 @@ impl BenchmarkCmd { .filter(|item| pallet.is_empty() || pallet == &b"*"[..] || pallet == &item.pallet[..]) .for_each(|item| { for benchmark in &item.benchmarks { - if extrinsic.is_empty() || - &extrinsic[..] == &b"*"[..] || - extrinsic == benchmark.name + if extrinsic.is_empty() || extrinsic == &b"*"[..] || extrinsic == benchmark.name { benchmarks_to_run.push(( item.pallet.clone(), diff --git a/utils/frame/try-runtime/cli/src/lib.rs b/utils/frame/try-runtime/cli/src/lib.rs index 2cd0a18909c19..32c814b0443d0 100644 --- a/utils/frame/try-runtime/cli/src/lib.rs +++ b/utils/frame/try-runtime/cli/src/lib.rs @@ -496,7 +496,6 @@ impl State { state_snapshot: snapshot_path.as_ref().map(SnapshotConfig::new), pallets: pallets.clone().unwrap_or_default(), at, - ..Default::default() })) .inject_hashed_key( &[twox_128(b"System"), twox_128(b"LastRuntimeUpgrade")].concat(), diff --git a/utils/frame/try-runtime/cli/src/parse.rs b/utils/frame/try-runtime/cli/src/parse.rs index a12e37344c7a3..15a0251ebc34a 100644 --- a/utils/frame/try-runtime/cli/src/parse.rs +++ b/utils/frame/try-runtime/cli/src/parse.rs @@ -18,8 +18,11 @@ //! Utils for parsing user input pub(crate) fn hash(block_hash: &str) -> Result { - let (block_hash, offset) = - if block_hash.starts_with("0x") { (&block_hash[2..], 2) } else { (block_hash, 0) }; + let (block_hash, offset) = if let Some(block_hash) = block_hash.strip_prefix("0x") { + (block_hash, 2) + } else { + (block_hash, 0) + }; if let Some(pos) = block_hash.chars().position(|c| !c.is_ascii_hexdigit()) { Err(format!(