diff --git a/substrate/.maintain/node-template-release/src/main.rs b/substrate/.maintain/node-template-release/src/main.rs index a1d85bf33f..bf37797419 100644 --- a/substrate/.maintain/node-template-release/src/main.rs +++ b/substrate/.maintain/node-template-release/src/main.rs @@ -99,8 +99,7 @@ fn replace_path_dependencies_with_git(cargo_toml_path: &Path, commit_id: &str, c let deps_rewritten = dependencies .iter() .filter_map(|(k, v)| v.clone().try_into::().ok().map(move |v| (k, v))) - .filter(|t| t.1.contains_key("path")) - .filter(|t| { + .filter(|t| t.1.contains_key("path") && { // if the path does not exists, we need to add this as git dependency t.1.get("path").unwrap().as_str().map(|path| !cargo_toml_path.join(path).exists()).unwrap_or(false) }) diff --git a/substrate/client/api/src/cht.rs b/substrate/client/api/src/cht.rs index 8fec00403b..96a5a27291 100644 --- a/substrate/client/api/src/cht.rs +++ b/substrate/client/api/src/cht.rs @@ -218,12 +218,9 @@ pub fn for_each_cht_group( let mut current_cht_num = None; let mut current_cht_blocks = Vec::new(); for block in blocks { - let new_cht_num = match block_to_cht_number(cht_size, block) { - Some(new_cht_num) => new_cht_num, - None => return Err(ClientError::Backend(format!( - "Cannot compute CHT root for the block #{}", block)).into() - ), - }; + let new_cht_num = block_to_cht_number(cht_size, block).ok_or_else(|| ClientError::Backend(format!( + "Cannot compute CHT root for the block #{}", block)) + )?; let advance_to_next_cht = current_cht_num.is_some() && current_cht_num != Some(new_cht_num); if advance_to_next_cht { diff --git a/substrate/client/api/src/in_mem.rs b/substrate/client/api/src/in_mem.rs index 930ae39c4b..409b5f52b5 100644 --- a/substrate/client/api/src/in_mem.rs +++ b/substrate/client/api/src/in_mem.rs @@ -226,10 +226,8 @@ impl Blockchain { /// Set an existing block as head. pub fn set_head(&self, id: BlockId) -> sp_blockchain::Result<()> { - let header = match self.header(id)? { - Some(h) => h, - None => return Err(sp_blockchain::Error::UnknownBlock(format!("{}", id))), - }; + let header = self.header(id)? + .ok_or_else(|| sp_blockchain::Error::UnknownBlock(format!("{}", id)))?; self.apply_head(&header) } @@ -760,10 +758,8 @@ impl backend::Backend for Backend where Block::Hash _ => {}, } - match self.blockchain.id(block).and_then(|id| self.states.read().get(&id).cloned()) { - Some(state) => Ok(state), - None => Err(sp_blockchain::Error::UnknownBlock(format!("{}", block))), - } + self.blockchain.id(block).and_then(|id| self.states.read().get(&id).cloned()) + .ok_or_else(|| sp_blockchain::Error::UnknownBlock(format!("{}", block))) } fn revert( diff --git a/substrate/client/api/src/notifications.rs b/substrate/client/api/src/notifications.rs index bfd419ec9a..b043a332d6 100644 --- a/substrate/client/api/src/notifications.rs +++ b/substrate/client/api/src/notifications.rs @@ -51,19 +51,18 @@ impl StorageChangeSet { .map(move |(k,v)| (None, k, v.as_ref())); let children = self.child_changes .iter() - .filter_map(move |(sk, changes)| { - if let Some(cf) = self.child_filters.as_ref() { - if let Some(filter) = cf.get(sk) { - Some(changes + .filter_map(move |(sk, changes)| + self.child_filters.as_ref().and_then(|cf| + cf.get(sk).map(|filter| changes .iter() .filter(move |&(key, _)| match filter { Some(ref filter) => filter.contains(key), None => true, }) - .map(move |(k,v)| (Some(sk), k, v.as_ref()))) - } else { None } - } else { None } - }) + .map(move |(k,v)| (Some(sk), k, v.as_ref())) + ) + ) + ) .flatten(); top.chain(children) } diff --git a/substrate/client/consensus/aura/src/import_queue.rs b/substrate/client/consensus/aura/src/import_queue.rs index 736c89aff6..0ec95d9412 100644 --- a/substrate/client/consensus/aura/src/import_queue.rs +++ b/substrate/client/consensus/aura/src/import_queue.rs @@ -72,10 +72,7 @@ fn check_header( C: sc_client_api::backend::AuxStore, P::Public: Encode + Decode + PartialEq + Clone, { - let seal = match header.digest_mut().pop() { - Some(x) => x, - None => return Err(Error::HeaderUnsealed(hash)), - }; + let seal = header.digest_mut().pop().ok_or_else(|| Error::HeaderUnsealed(hash))?; let sig = seal.as_aura_seal().ok_or_else(|| { aura_err(Error::HeaderBadSeal(hash)) @@ -89,10 +86,8 @@ fn check_header( } else { // check the signature is valid under the expected authority and // chain state. - let expected_author = match slot_author::

(slot, &authorities) { - None => return Err(Error::SlotAuthorNotFound), - Some(author) => author, - }; + let expected_author = slot_author::

(slot, &authorities) + .ok_or_else(|| Error::SlotAuthorNotFound)?; let pre_hash = header.hash(); diff --git a/substrate/client/consensus/babe/src/verification.rs b/substrate/client/consensus/babe/src/verification.rs index 53dfd9ed10..469286f511 100644 --- a/substrate/client/consensus/babe/src/verification.rs +++ b/substrate/client/consensus/babe/src/verification.rs @@ -71,10 +71,8 @@ pub(super) fn check_header( let pre_digest = pre_digest.map(Ok).unwrap_or_else(|| find_pre_digest::(&header))?; trace!(target: "babe", "Checking header"); - let seal = match header.digest_mut().pop() { - Some(x) => x, - None => return Err(babe_err(Error::HeaderUnsealed(header.hash()))), - }; + let seal = header.digest_mut().pop() + .ok_or_else(|| babe_err(Error::HeaderUnsealed(header.hash())))?; let sig = seal.as_babe_seal().ok_or_else(|| { babe_err(Error::HeaderBadSeal(header.hash())) diff --git a/substrate/client/consensus/manual-seal/src/seal_block.rs b/substrate/client/consensus/manual-seal/src/seal_block.rs index b21630f037..a8050efb9a 100644 --- a/substrate/client/consensus/manual-seal/src/seal_block.rs +++ b/substrate/client/consensus/manual-seal/src/seal_block.rs @@ -104,10 +104,7 @@ pub async fn seal_block( // or fetch the best_block. let parent = match parent_hash { Some(hash) => { - match client.header(BlockId::Hash(hash))? { - Some(header) => header, - None => return Err(Error::BlockNotFound(format!("{}", hash))), - } + client.header(BlockId::Hash(hash))?.ok_or_else(|| Error::BlockNotFound(format!("{}", hash)))? } None => select_chain.best_chain()? }; diff --git a/substrate/client/consensus/slots/src/lib.rs b/substrate/client/consensus/slots/src/lib.rs index 1436f5f5c2..c1638fb566 100644 --- a/substrate/client/consensus/slots/src/lib.rs +++ b/substrate/client/consensus/slots/src/lib.rs @@ -256,10 +256,7 @@ pub trait SimpleSlotWorker { return None; } - let claim = match self.claim_slot(&chain_head, slot, &epoch_data) { - None => return None, - Some(claim) => claim, - }; + let claim = self.claim_slot(&chain_head, slot, &epoch_data)?; if self.should_backoff(slot, &chain_head) { return None; diff --git a/substrate/client/consensus/slots/src/slots.rs b/substrate/client/consensus/slots/src/slots.rs index 4057a6d0d1..1d89ba3bf9 100644 --- a/substrate/client/consensus/slots/src/slots.rs +++ b/substrate/client/consensus/slots/src/slots.rs @@ -135,10 +135,7 @@ impl Slots { Err(err) => return Err(sp_consensus::Error::InherentData(err)), }; let result = self.timestamp_extractor.extract_timestamp_and_slot(&inherent_data); - let (timestamp, slot, offset) = match result { - Ok(v) => v, - Err(err) => return Err(err), - }; + let (timestamp, slot, offset) = result?; // reschedule delay for next slot. let ends_in = offset + time_until_next(timestamp.as_duration(), self.slot_duration); diff --git a/substrate/client/db/src/changes_tries_storage.rs b/substrate/client/db/src/changes_tries_storage.rs index 8051adc183..860ca41730 100644 --- a/substrate/client/db/src/changes_tries_storage.rs +++ b/substrate/client/db/src/changes_tries_storage.rs @@ -503,10 +503,8 @@ fn read_tries_meta( meta_column: u32, ) -> ClientResult> { match db.get(meta_column, meta_keys::CHANGES_TRIES_META) { - Some(h) => match Decode::decode(&mut &h[..]) { - Ok(h) => Ok(h), - Err(err) => Err(ClientError::Backend(format!("Error decoding changes tries metadata: {}", err))), - }, + Some(h) => Decode::decode(&mut &h[..]) + .map_err(|err| ClientError::Backend(format!("Error decoding changes tries metadata: {}", err))), None => Ok(ChangesTriesMeta { oldest_digest_range: None, oldest_pruned_digest_range_end: Zero::zero(), diff --git a/substrate/client/db/src/utils.rs b/substrate/client/db/src/utils.rs index 590b994d50..7f82cb8489 100644 --- a/substrate/client/db/src/utils.rs +++ b/substrate/client/db/src/utils.rs @@ -395,10 +395,8 @@ pub fn read_meta(db: &dyn Database, col_header: u32) -> Result< }; let load_meta_block = |desc, key| -> Result<_, sp_blockchain::Error> { - if let Some(Some(header)) = match db.get(COLUMN_META, key) { - Some(id) => db.get(col_header, &id).map(|b| Block::Header::decode(&mut &b[..]).ok()), - None => None, - } + if let Some(Some(header)) = db.get(COLUMN_META, key) + .and_then(|id| db.get(col_header, &id).map(|b| Block::Header::decode(&mut &b[..]).ok())) { let hash = header.hash(); debug!( diff --git a/substrate/client/finality-grandpa/src/import.rs b/substrate/client/finality-grandpa/src/import.rs index b2fcca019b..482859b1f7 100644 --- a/substrate/client/finality-grandpa/src/import.rs +++ b/substrate/client/finality-grandpa/src/import.rs @@ -289,14 +289,10 @@ where fn consume( mut self, ) -> Option<(AuthoritySet, SharedDataLocked<'a, AuthoritySet>)> { - if let Some(old) = self.old.take() { - Some(( + self.old.take().map(|old| ( old, self.guard.take().expect("only taken on deconstruction; qed"), - )) - } else { - None - } + )) } } diff --git a/substrate/client/finality-grandpa/src/lib.rs b/substrate/client/finality-grandpa/src/lib.rs index fb9ecaa2c1..e1c3a2c131 100644 --- a/substrate/client/finality-grandpa/src/lib.rs +++ b/substrate/client/finality-grandpa/src/lib.rs @@ -1134,13 +1134,12 @@ fn local_authority_id( voters: &VoterSet, keystore: Option<&SyncCryptoStorePtr>, ) -> Option { - match keystore { - Some(keystore) => voters - .iter() - .find(|(p, _)| { - SyncCryptoStore::has_keys(&**keystore, &[(p.to_raw_vec(), AuthorityId::ID)]) - }) - .map(|(p, _)| p.clone()), - None => None, - } + keystore.and_then(|keystore| { + voters + .iter() + .find(|(p, _)| { + SyncCryptoStore::has_keys(&**keystore, &[(p.to_raw_vec(), AuthorityId::ID)]) + }) + .map(|(p, _)| p.clone()) + }) } diff --git a/substrate/client/light/src/fetcher.rs b/substrate/client/light/src/fetcher.rs index b71c487180..e39cfe07fb 100644 --- a/substrate/client/light/src/fetcher.rs +++ b/substrate/client/light/src/fetcher.rs @@ -330,10 +330,7 @@ impl<'a, H, Number, Hash> ChangesTrieRootsStorage for RootsStorage<'a self.prev_roots.get(&Number::unique_saturated_from(block)).cloned() } else { let index: Option = block.checked_sub(&self.roots.0).and_then(|index| index.checked_into()); - match index { - Some(index) => self.roots.1.get(index as usize).cloned(), - None => None, - } + index.and_then(|index| self.roots.1.get(index as usize).cloned()) }; Ok(root.map(|root| { diff --git a/substrate/client/offchain/src/api/http.rs b/substrate/client/offchain/src/api/http.rs index dbe8e55b36..f03f7a93b8 100644 --- a/substrate/client/offchain/src/api/http.rs +++ b/substrate/client/offchain/src/api/http.rs @@ -183,10 +183,7 @@ impl HttpApi { ) -> Result<(), HttpError> { // Extract the request from the list. // Don't forget to add it back if necessary when returning. - let mut request = match self.requests.remove(&request_id) { - None => return Err(HttpError::Invalid), - Some(r) => r, - }; + let mut request = self.requests.remove(&request_id).ok_or_else(|| HttpError::Invalid)?; let mut deadline = timestamp::deadline_to_future(deadline); // Closure that writes data to a sender, taking the deadline into account. Can return `Ok` diff --git a/substrate/client/peerset/src/peersstate.rs b/substrate/client/peerset/src/peersstate.rs index c200d2729e..309c7e6b8f 100644 --- a/substrate/client/peerset/src/peersstate.rs +++ b/substrate/client/peerset/src/peersstate.rs @@ -272,15 +272,11 @@ impl PeersState { }) .map(|(peer_id, _)| peer_id.clone()); - if let Some(peer_id) = outcome { - Some(NotConnectedPeer { + outcome.map(move |peer_id| NotConnectedPeer { state: self, set, peer_id: Cow::Owned(peer_id), }) - } else { - None - } } /// Returns `true` if there is a free outgoing slot available related to this set. diff --git a/substrate/client/rpc/src/state/state_light.rs b/substrate/client/rpc/src/state/state_light.rs index c8c9213458..4bc4b07727 100644 --- a/substrate/client/rpc/src/state/state_light.rs +++ b/substrate/client/rpc/src/state/state_light.rs @@ -722,13 +722,10 @@ fn maybe_share_remote_request(future: F) -> impl std::future::Future> where F: std::future::Future> { - future.then(|result| ready(match result { - Ok(result) => Ok(result), - Err(err) => { + future.then(|result| ready(result.or_else(|err| { warn!("Remote request for subscription data has failed with: {:?}", err); Err(()) - }, - })) + }))) } /// Convert successful future result into Ok(Some(result)) and error into Ok(None), diff --git a/substrate/client/service/src/client/client.rs b/substrate/client/service/src/client/client.rs index f975961c3b..f05a275199 100644 --- a/substrate/client/service/src/client/client.rs +++ b/substrate/client/service/src/client/client.rs @@ -585,10 +585,8 @@ impl Client where &dyn PrunableStateChangesTrieStorage, Vec<(NumberFor, Option<(NumberFor, Block::Hash)>, ChangesTrieConfiguration)>, )> { - let storage = match self.backend.changes_trie_storage() { - Some(storage) => storage, - None => return Err(sp_blockchain::Error::ChangesTriesNotSupported), - }; + let storage = self.backend.changes_trie_storage() + .ok_or_else(|| sp_blockchain::Error::ChangesTriesNotSupported)?; let mut configs = Vec::with_capacity(1); let mut current = last; @@ -1153,10 +1151,8 @@ impl Client where /// Gets the uncles of the block with `target_hash` going back `max_generation` ancestors. pub fn uncles(&self, target_hash: Block::Hash, max_generation: NumberFor) -> sp_blockchain::Result> { let load_header = |id: Block::Hash| -> sp_blockchain::Result { - match self.backend.blockchain().header(BlockId::Hash(id))? { - Some(hdr) => Ok(hdr), - None => Err(Error::UnknownBlock(format!("{:?}", id))), - } + self.backend.blockchain().header(BlockId::Hash(id))? + .ok_or_else(|| Error::UnknownBlock(format!("{:?}", id))) }; let genesis_hash = self.backend.blockchain().info().genesis_hash; diff --git a/substrate/client/service/src/lib.rs b/substrate/client/service/src/lib.rs index 4ca784558d..db5f296953 100644 --- a/substrate/client/service/src/lib.rs +++ b/substrate/client/service/src/lib.rs @@ -391,9 +391,8 @@ fn start_rpc_servers< ) -> Result, error::Error> { fn maybe_start_server(address: Option, mut start: F) -> Result, io::Error> where F: FnMut(&SocketAddr) -> Result, - { - Ok(match address { - Some(mut address) => Some(start(&address) + { + address.map(|mut address| start(&address) .or_else(|e| match e.kind() { io::ErrorKind::AddrInUse | io::ErrorKind::PermissionDenied => { @@ -402,10 +401,9 @@ fn start_rpc_servers< start(&address) }, _ => Err(e), - })?), - None => None, - }) - } + } + ) ).transpose() + } fn deny_unsafe(addr: &SocketAddr, methods: &RpcMethods) -> sc_rpc::DenyUnsafe { let is_exposed_addr = !addr.ip().is_loopback(); diff --git a/substrate/client/state-db/src/noncanonical.rs b/substrate/client/state-db/src/noncanonical.rs index 8eaa8a02f5..3f0c7d132f 100644 --- a/substrate/client/state-db/src/noncanonical.rs +++ b/substrate/client/state-db/src/noncanonical.rs @@ -150,10 +150,8 @@ impl NonCanonicalOverlay { pub fn new(db: &D) -> Result, Error> { let last_canonicalized = db.get_meta(&to_meta_key(LAST_CANONICAL, &())) .map_err(|e| Error::Db(e))?; - let last_canonicalized = match last_canonicalized { - Some(buffer) => Some(<(BlockHash, u64)>::decode(&mut buffer.as_slice())?), - None => None, - }; + let last_canonicalized = last_canonicalized + .map(|buffer| <(BlockHash, u64)>::decode(&mut buffer.as_slice())).transpose()?; let mut levels = VecDeque::new(); let mut parents = HashMap::new(); let mut values = HashMap::new(); diff --git a/substrate/client/telemetry/src/lib.rs b/substrate/client/telemetry/src/lib.rs index 8d3b605db0..5c233d5490 100644 --- a/substrate/client/telemetry/src/lib.rs +++ b/substrate/client/telemetry/src/lib.rs @@ -389,10 +389,7 @@ impl Telemetry { /// The `connection_message` argument is a JSON object that is sent every time the connection /// (re-)establishes. pub fn start_telemetry(&mut self, connection_message: ConnectionMessage) -> Result<()> { - let endpoints = match self.endpoints.take() { - Some(x) => x, - None => return Err(Error::TelemetryAlreadyInitialized), - }; + let endpoints = self.endpoints.take().ok_or_else(|| Error::TelemetryAlreadyInitialized)?; self.register_sender .unbounded_send(Register::Telemetry { diff --git a/substrate/client/tracing/src/lib.rs b/substrate/client/tracing/src/lib.rs index 41947d4c0e..54620d30bb 100644 --- a/substrate/client/tracing/src/lib.rs +++ b/substrate/client/tracing/src/lib.rs @@ -246,7 +246,7 @@ fn parse_target(s: &str) -> (String, Level) { Some(i) => { let target = s[0..i].to_string(); if s.len() > i { - let level = s[i + 1..s.len()].parse::().unwrap_or(Level::TRACE); + let level = s[i + 1..].parse::().unwrap_or(Level::TRACE); (target, level) } else { (target, Level::TRACE) diff --git a/substrate/client/transaction-pool/graph/src/pool.rs b/substrate/client/transaction-pool/graph/src/pool.rs index 8a60ea80bc..7f9bc3c757 100644 --- a/substrate/client/transaction-pool/graph/src/pool.rs +++ b/substrate/client/transaction-pool/graph/src/pool.rs @@ -322,10 +322,7 @@ impl Pool { ) -> Result<(), B::Error> { log::debug!(target: "txpool", "Pruning at {:?}", at); // Prune all transactions that provide given tags - let prune_status = match self.validated_pool.prune_tags(tags) { - Ok(prune_status) => prune_status, - Err(e) => return Err(e), - }; + let prune_status = self.validated_pool.prune_tags(tags)?; // Make sure that we don't revalidate extrinsics that were part of the recently // imported block. This is especially important for UTXO-like chains cause the diff --git a/substrate/client/transaction-pool/graph/src/ready.rs b/substrate/client/transaction-pool/graph/src/ready.rs index 4ede9241d8..7946f49e6a 100644 --- a/substrate/client/transaction-pool/graph/src/ready.rs +++ b/substrate/client/transaction-pool/graph/src/ready.rs @@ -527,12 +527,9 @@ impl Iterator for BestIterator { satisfied += 1; Some((satisfied, tx_ref)) // then get from the pool - } else if let Some(next) = self.all.read().get(hash) { - Some((next.requires_offset + 1, next.transaction.clone())) } else { - None + self.all.read().get(hash).map(|next| (next.requires_offset + 1, next.transaction.clone())) }; - if let Some((satisfied, tx_ref)) = res { self.best_or_awaiting(satisfied, tx_ref) } diff --git a/substrate/frame/assets/src/functions.rs b/substrate/frame/assets/src/functions.rs index 3f2abe0617..13c92f781b 100644 --- a/substrate/frame/assets/src/functions.rs +++ b/substrate/frame/assets/src/functions.rs @@ -163,10 +163,7 @@ impl, I: 'static> Pallet { who: &T::AccountId, keep_alive: bool, ) -> Result> { - let details = match Asset::::get(id) { - Some(details) => details, - None => return Err(Error::::Unknown), - }; + let details = Asset::::get(id).ok_or_else(|| Error::::Unknown)?; ensure!(!details.is_frozen, Error::::Frozen); let account = Account::::get(id, who); diff --git a/substrate/frame/authorship/src/lib.rs b/substrate/frame/authorship/src/lib.rs index da4b66f229..a7803319c5 100644 --- a/substrate/frame/authorship/src/lib.rs +++ b/substrate/frame/authorship/src/lib.rs @@ -490,10 +490,7 @@ mod tests { let pre_runtime_digests = header.digest.logs.iter().filter_map(|d| d.as_pre_runtime()); let seals = header.digest.logs.iter().filter_map(|d| d.as_seal()); - let author = match AuthorGiven::find_author(pre_runtime_digests) { - None => return Err("no author"), - Some(author) => author, - }; + let author = AuthorGiven::find_author(pre_runtime_digests).ok_or_else(|| "no author")?; for (id, seal) in seals { if id == TEST_ID { diff --git a/substrate/frame/contracts/src/gas.rs b/substrate/frame/contracts/src/gas.rs index 21c1afbcd6..31cc5fad30 100644 --- a/substrate/frame/contracts/src/gas.rs +++ b/substrate/frame/contracts/src/gas.rs @@ -127,10 +127,7 @@ where } let amount = token.calculate_amount(metadata); - let new_value = match self.gas_left.checked_sub(amount) { - None => None, - Some(val) => Some(val), - }; + let new_value = self.gas_left.checked_sub(amount); // We always consume the gas even if there is not enough gas. self.gas_left = new_value.unwrap_or_else(Zero::zero); diff --git a/substrate/frame/contracts/src/migration.rs b/substrate/frame/contracts/src/migration.rs index 2e10f4b7ff..4fc138d3f3 100644 --- a/substrate/frame/contracts/src/migration.rs +++ b/substrate/frame/contracts/src/migration.rs @@ -26,16 +26,12 @@ pub fn migrate() -> Weight { Some(version) if version == PalletVersion::new(3, 0, 0) => { weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 1)); let _ = >::translate::(|version| { - if let Some(version) = version { - Some(Schedule { + version.map(|version| Schedule { version: version.saturating_add(1), // Default limits were not decreased. Therefore it is OK to overwrite // the schedule with the new defaults. .. Default::default() }) - } else { - None - } }); } _ => (), diff --git a/substrate/frame/contracts/src/rent.rs b/substrate/frame/contracts/src/rent.rs index 321fe151c3..6e268c48bc 100644 --- a/substrate/frame/contracts/src/rent.rs +++ b/substrate/frame/contracts/src/rent.rs @@ -407,10 +407,7 @@ where ); // Check what happened after enaction of the verdict. - let alive_contract_info = match new_contract_info.map_err(|_| IsTombstone)? { - None => return Err(IsTombstone), - Some(contract) => contract, - }; + let alive_contract_info = new_contract_info.map_err(|_| IsTombstone)?.ok_or_else(|| IsTombstone)?; // Compute how much would the fee per block be with the *updated* balance. let total_balance = T::Currency::total_balance(account); diff --git a/substrate/frame/democracy/src/lib.rs b/substrate/frame/democracy/src/lib.rs index b3b37b0b34..351204bfcb 100644 --- a/substrate/frame/democracy/src/lib.rs +++ b/substrate/frame/democracy/src/lib.rs @@ -1653,10 +1653,7 @@ impl Module { // To decode the enum variant we only need the first byte. let mut buf = [0u8; 1]; let key = >::hashed_key_for(proposal_hash); - let bytes = match sp_io::storage::read(&key, &mut buf, 0) { - Some(bytes) => bytes, - None => return Err(Error::::NotImminent.into()), - }; + let bytes = sp_io::storage::read(&key, &mut buf, 0).ok_or_else(|| Error::::NotImminent)?; // The value may be smaller that 1 byte. let mut input = &buf[0..buf.len().min(bytes as usize)]; @@ -1684,10 +1681,7 @@ impl Module { // * at most 5 bytes to decode a `Compact` let mut buf = [0u8; 6]; let key = >::hashed_key_for(proposal_hash); - let bytes = match sp_io::storage::read(&key, &mut buf, 0) { - Some(bytes) => bytes, - None => return Err(Error::::PreimageMissing.into()), - }; + let bytes = sp_io::storage::read(&key, &mut buf, 0).ok_or_else(|| Error::::PreimageMissing)?; // The value may be smaller that 6 bytes. let mut input = &buf[0..buf.len().min(bytes as usize)]; @@ -1761,10 +1755,7 @@ impl Module { fn decode_compact_u32_at(key: &[u8]) -> Option { // `Compact` takes at most 5 bytes. let mut buf = [0u8; 5]; - let bytes = match sp_io::storage::read(&key, &mut buf, 0) { - Some(bytes) => bytes, - None => return None, - }; + let bytes = sp_io::storage::read(&key, &mut buf, 0)?; // The value may be smaller than 5 bytes. let mut input = &buf[0..buf.len().min(bytes as usize)]; match codec::Compact::::decode(&mut input) { diff --git a/substrate/frame/grandpa/src/lib.rs b/substrate/frame/grandpa/src/lib.rs index eb3dc4f110..7cfc1d61ba 100644 --- a/substrate/frame/grandpa/src/lib.rs +++ b/substrate/frame/grandpa/src/lib.rs @@ -518,21 +518,13 @@ impl Module { None } else { let session_index = - if let Some(session_id) = Self::session_for_set(set_id - 1) { - session_id - } else { - return Err(Error::::InvalidEquivocationProof.into()); - }; + Self::session_for_set(set_id - 1).ok_or_else(|| Error::::InvalidEquivocationProof)?; Some(session_index) }; let set_id_session_index = - if let Some(session_id) = Self::session_for_set(set_id) { - session_id - } else { - return Err(Error::::InvalidEquivocationProof.into()); - }; + Self::session_for_set(set_id).ok_or_else(|| Error::::InvalidEquivocationProof)?; // check that the session id for the membership proof is within the // bounds of the set id reported in the equivocation. diff --git a/substrate/frame/staking/src/lib.rs b/substrate/frame/staking/src/lib.rs index c938dceb76..4252eae50d 100644 --- a/substrate/frame/staking/src/lib.rs +++ b/substrate/frame/staking/src/lib.rs @@ -2736,11 +2736,8 @@ impl Convert for ExposureOf { fn convert(validator: T::AccountId) -> Option>> { - if let Some(active_era) = >::active_era() { - Some(>::eras_stakers(active_era.index, &validator)) - } else { - None - } + >::active_era() + .map(|active_era| >::eras_stakers(active_era.index, &validator)) } } diff --git a/substrate/frame/support/src/storage/generator/value.rs b/substrate/frame/support/src/storage/generator/value.rs index 093dcb305e..e07c952320 100644 --- a/substrate/frame/support/src/storage/generator/value.rs +++ b/substrate/frame/support/src/storage/generator/value.rs @@ -77,10 +77,8 @@ impl> storage::StorageValue for G { let key = Self::storage_value_final_key(); // attempt to get the length directly. - let maybe_old = match unhashed::get_raw(&key) { - Some(old_data) => Some(O::decode(&mut &old_data[..]).map_err(|_| ())?), - None => None, - }; + let maybe_old = unhashed::get_raw(&key) + .map(|old_data| O::decode(&mut &old_data[..]).map_err(|_| ())).transpose()?; let maybe_new = f(maybe_old); if let Some(new) = maybe_new.as_ref() { new.using_encoded(|d| unhashed::put_raw(&key, d)); diff --git a/substrate/primitives/api/proc-macro/src/utils.rs b/substrate/primitives/api/proc-macro/src/utils.rs index 2e4ccf8ff4..aa3c69d46a 100644 --- a/substrate/primitives/api/proc-macro/src/utils.rs +++ b/substrate/primitives/api/proc-macro/src/utils.rs @@ -195,7 +195,7 @@ pub fn extract_all_signature_types(items: &[ImplItem]) -> Vec { ImplItem::Method(method) => Some(&method.sig), _ => None, }) - .map(|sig| { + .flat_map(|sig| { let ret_ty = match &sig.output { ReturnType::Default => None, ReturnType::Type(_, ty) => Some((**ty).clone()), @@ -209,7 +209,6 @@ pub fn extract_all_signature_types(items: &[ImplItem]) -> Vec { _ => (**ty).clone(), }).chain(ret_ty) }) - .flatten() .collect() } diff --git a/substrate/primitives/consensus/common/src/block_import.rs b/substrate/primitives/consensus/common/src/block_import.rs index 8d01da64b4..6e4fb98865 100644 --- a/substrate/primitives/consensus/common/src/block_import.rs +++ b/substrate/primitives/consensus/common/src/block_import.rs @@ -237,13 +237,10 @@ impl BlockImportParams { pub fn take_intermediate(&mut self, key: &[u8]) -> Result, Error> { let (k, v) = self.intermediates.remove_entry(key).ok_or(Error::NoIntermediate)?; - match v.downcast::() { - Ok(v) => Ok(v), - Err(v) => { + v.downcast::().or_else(|v| { self.intermediates.insert(k, v); Err(Error::InvalidIntermediate) - }, - } + }) } /// Get a reference to a given intermediate. diff --git a/substrate/utils/frame/rpc/system/src/lib.rs b/substrate/utils/frame/rpc/system/src/lib.rs index 57c0cda9cc..bbc51a28a5 100644 --- a/substrate/utils/frame/rpc/system/src/lib.rs +++ b/substrate/utils/frame/rpc/system/src/lib.rs @@ -207,10 +207,7 @@ where let call_data = account.encode(); let future_best_header = future_best_header .and_then(move |maybe_best_header| ready( - match maybe_best_header { - Some(best_header) => Ok(best_header), - None => Err(ClientError::UnknownBlock(format!("{}", best_hash))), - } + maybe_best_header.ok_or_else(|| { ClientError::UnknownBlock(format!("{}", best_hash)) }) )); let future_nonce = future_best_header.and_then(move |best_header| fetcher.remote_call(RemoteCallRequest { diff --git a/substrate/utils/frame/try-runtime/cli/src/lib.rs b/substrate/utils/frame/try-runtime/cli/src/lib.rs index 8e407f3b2d..4d265c0995 100644 --- a/substrate/utils/frame/try-runtime/cli/src/lib.rs +++ b/substrate/utils/frame/try-runtime/cli/src/lib.rs @@ -169,10 +169,8 @@ impl TryRuntimeCmd { uri: url.into(), state_snapshot: snapshot_path.as_ref().map(SnapshotConfig::new), modules: modules.clone().unwrap_or_default(), - at: match block_at { - Some(b) => Some(b.parse().map_err(|e| format!("Could not parse hash: {:?}", e))?), - None => None, - }, + at: block_at.as_ref() + .map(|b| b.parse().map_err(|e| format!("Could not parse hash: {:?}", e))).transpose()?, ..Default::default() })), };