From 11ab894256a1edc2a68234134f7922fa7b42e1d7 Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Thu, 8 Apr 2021 20:01:20 +0000 Subject: [PATCH] [easy, cleanup] Simplify some pattern-matches (bp #16402) (#16445) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Simplify some pattern-matches (#16402) When those match an exact combinator on Option / Result. Tool-aided by [comby-rust](https://github.com/huitseeker/comby-rust). (cherry picked from commit b08cff9e778691db68bddedfceae85b6bfd53b47) # Conflicts: # accounts-cluster-bench/src/main.rs # core/src/rpc.rs # runtime/src/accounts_hash.rs # runtime/src/message_processor.rs * Fix conflicts Co-authored-by: François Garillot <4142+huitseeker@users.noreply.github.com> Co-authored-by: Tyera Eulberg --- cli/src/program.rs | 24 ++++++------------------ client/src/nonce_utils.rs | 5 +---- core/src/cluster_slots.rs | 3 +-- core/src/crds.rs | 6 ++++-- core/src/duplicate_shred.rs | 5 +---- core/src/rpc.rs | 18 ++++++++---------- ledger-tool/src/main.rs | 7 ++++--- ledger/src/blockstore.rs | 9 ++------- ledger/src/leader_schedule_cache.rs | 4 +--- net-utils/src/lib.rs | 3 +-- programs/bpf_loader/src/syscalls.rs | 18 ++++++------------ runtime/src/message_processor.rs | 5 ++++- sdk/program/src/instruction.rs | 5 +---- storage-bigtable/src/bigtable.rs | 5 +---- storage-proto/src/convert.rs | 26 +++++++------------------- tokens/src/arg_parser.rs | 19 ++++++++++--------- 16 files changed, 58 insertions(+), 104 deletions(-) diff --git a/cli/src/program.rs b/cli/src/program.rs index 364bfd799c..0704892aa4 100644 --- a/cli/src/program.rs +++ b/cli/src/program.rs @@ -386,22 +386,17 @@ pub fn parse_program_subcommand( default_signer.signer_from_path(matches, wallet_manager)?, )]; - let program_location = if let Some(location) = matches.value_of("program_location") { - Some(location.to_string()) - } else { - None - }; + let program_location = matches + .value_of("program_location") + .map(|location| location.to_string()); let buffer_pubkey = if let Ok((buffer_signer, Some(buffer_pubkey))) = signer_of(matches, "buffer", wallet_manager) { bulk_signers.push(buffer_signer); Some(buffer_pubkey) - } else if let Some(buffer_pubkey) = pubkey_of_signer(matches, "buffer", wallet_manager)? - { - Some(buffer_pubkey) } else { - None + pubkey_of_signer(matches, "buffer", wallet_manager)? }; let program_pubkey = if let Ok((program_signer, Some(program_pubkey))) = @@ -409,12 +404,8 @@ pub fn parse_program_subcommand( { bulk_signers.push(program_signer); Some(program_pubkey) - } else if let Some(program_pubkey) = - pubkey_of_signer(matches, "program_id", wallet_manager)? - { - Some(program_pubkey) } else { - None + pubkey_of_signer(matches, "program_id", wallet_manager)? }; let upgrade_authority_pubkey = @@ -463,11 +454,8 @@ pub fn parse_program_subcommand( { bulk_signers.push(buffer_signer); Some(buffer_pubkey) - } else if let Some(buffer_pubkey) = pubkey_of_signer(matches, "buffer", wallet_manager)? - { - Some(buffer_pubkey) } else { - None + pubkey_of_signer(matches, "buffer", wallet_manager)? }; let buffer_authority_pubkey = diff --git a/client/src/nonce_utils.rs b/client/src/nonce_utils.rs index 5a2d448380..310087867a 100644 --- a/client/src/nonce_utils.rs +++ b/client/src/nonce_utils.rs @@ -46,10 +46,7 @@ pub fn get_account_with_commitment( .value .ok_or_else(|| Error::Client(format!("AccountNotFound: pubkey={}", nonce_pubkey))) }) - .and_then(|a| match account_identity_ok(&a) { - Ok(()) => Ok(a), - Err(e) => Err(e), - }) + .and_then(|a| account_identity_ok(&a).map(|()| a)) } pub fn account_identity_ok(account: &Account) -> Result<(), Error> { diff --git a/core/src/cluster_slots.rs b/core/src/cluster_slots.rs index e2d2e06d74..46e909158e 100644 --- a/core/src/cluster_slots.rs +++ b/core/src/cluster_slots.rs @@ -190,8 +190,7 @@ impl ClusterSlots { .read() .unwrap() .keys() - .filter(|x| **x > root) - .filter(|x| !my_slots.contains(*x)) + .filter(|x| **x > root && !my_slots.contains(*x)) .map(|x| RepairType::HighestShred(*x, 0)) .collect() } diff --git a/core/src/crds.rs b/core/src/crds.rs index af1c53015c..ed711ca5ce 100644 --- a/core/src/crds.rs +++ b/core/src/crds.rs @@ -688,8 +688,10 @@ mod test { let num_epoch_slots = crds .table .values() - .filter(|value| value.insert_timestamp >= since) - .filter(|value| matches!(value.value.data, CrdsData::EpochSlots(_, _))) + .filter(|value| { + value.insert_timestamp >= since + && matches!(value.value.data, CrdsData::EpochSlots(_, _)) + }) .count(); assert_eq!(num_epoch_slots, crds.get_epoch_slots_since(since).count()); for value in crds.get_epoch_slots_since(since) { diff --git a/core/src/duplicate_shred.rs b/core/src/duplicate_shred.rs index b9193b9c8b..47cec81db0 100644 --- a/core/src/duplicate_shred.rs +++ b/core/src/duplicate_shred.rs @@ -226,10 +226,7 @@ pub fn into_shreds( chunk_index, chunk, .. - } = match chunks.next() { - None => return Err(Error::InvalidDuplicateShreds), - Some(chunk) => chunk, - }; + } = chunks.next().ok_or(Error::InvalidDuplicateShreds)?; let slot_leader = leader(slot).ok_or(Error::UnknownSlotLeader)?; let check_chunk = check_chunk(slot, shred_index, shred_type, num_chunks); let mut data = HashMap::new(); diff --git a/core/src/rpc.rs b/core/src/rpc.rs index df33f1d602..f4f60556fb 100644 --- a/core/src/rpc.rs +++ b/core/src/rpc.rs @@ -3185,16 +3185,14 @@ impl RpcSol for RpcSolImpl { let address = verify_pubkey(address)?; let config = config.unwrap_or_default(); - let before = if let Some(before) = config.before { - Some(verify_signature(&before)?) - } else { - None - }; - let until = if let Some(until) = config.until { - Some(verify_signature(&until)?) - } else { - None - }; + let before = config + .before + .map(|ref before| verify_signature(before)) + .transpose()?; + let until = config + .until + .map(|ref until| verify_signature(until)) + .transpose()?; let limit = config .limit .unwrap_or(MAX_GET_CONFIRMED_SIGNATURES_FOR_ADDRESS2_LIMIT); diff --git a/ledger-tool/src/main.rs b/ledger-tool/src/main.rs index 8e2f7d8e74..c9f7d7113e 100644 --- a/ledger-tool/src/main.rs +++ b/ledger-tool/src/main.rs @@ -1645,10 +1645,11 @@ fn main() { let parse_results = { if let Some(slot_string) = frozen_regex.captures_iter(&line).next() { Some((slot_string, &mut frozen)) - } else if let Some(slot_string) = full_regex.captures_iter(&line).next() { - Some((slot_string, &mut full)) } else { - None + full_regex + .captures_iter(&line) + .next() + .map(|slot_string| (slot_string, &mut full)) } }; diff --git a/ledger/src/blockstore.rs b/ledger/src/blockstore.rs index f2473c0365..4162e36646 100644 --- a/ledger/src/blockstore.rs +++ b/ledger/src/blockstore.rs @@ -2424,10 +2424,7 @@ impl Blockstore { for (slot, signature) in address_signatures.into_iter() { let transaction_status = self.get_transaction_status(signature, &confirmed_unrooted_slots)?; - let err = match transaction_status { - None => None, - Some((_slot, status)) => status.status.err(), - }; + let err = transaction_status.and_then(|(_slot, status)| status.status.err()); let block_time = self.get_block_time(slot)?; infos.push(ConfirmedTransactionStatusWithSignature { signature, @@ -3178,10 +3175,8 @@ fn find_slot_meta_in_cached_state<'a>( ) -> Option>> { if let Some(entry) = working_set.get(&slot) { Some(entry.new_slot_meta.clone()) - } else if let Some(entry) = chained_slots.get(&slot) { - Some(entry.clone()) } else { - None + chained_slots.get(&slot).cloned() } } diff --git a/ledger/src/leader_schedule_cache.rs b/ledger/src/leader_schedule_cache.rs index d82d2f9014..3f44c84324 100644 --- a/ledger/src/leader_schedule_cache.rs +++ b/ledger/src/leader_schedule_cache.rs @@ -212,10 +212,8 @@ impl LeaderScheduleCache { let epoch_schedule = self.get_epoch_leader_schedule(epoch); if epoch_schedule.is_some() { epoch_schedule - } else if let Some(epoch_schedule) = self.compute_epoch_schedule(epoch, bank) { - Some(epoch_schedule) } else { - None + self.compute_epoch_schedule(epoch, bank) } } diff --git a/net-utils/src/lib.rs b/net-utils/src/lib.rs index 99619c21d2..6c66f3d7fd 100644 --- a/net-utils/src/lib.rs +++ b/net-utils/src/lib.rs @@ -198,8 +198,7 @@ fn do_verify_reachable_ports( .collect::>(), checked_ports_and_sockets .iter() - .map(|(_, sockets)| sockets) - .flatten(), + .flat_map(|(_, sockets)| sockets), ); let _ = ip_echo_server_request( diff --git a/programs/bpf_loader/src/syscalls.rs b/programs/bpf_loader/src/syscalls.rs index a75bdae17d..7f430846f0 100644 --- a/programs/bpf_loader/src/syscalls.rs +++ b/programs/bpf_loader/src/syscalls.rs @@ -322,10 +322,8 @@ fn translate_type_inner<'a, T>( Err(SyscallError::UnalignedPointer.into()) } else { unsafe { - match translate(memory_mapping, access_type, vm_addr, size_of::() as u64) { - Ok(value) => Ok(&mut *(value as *mut T)), - Err(e) => Err(e), - } + translate(memory_mapping, access_type, vm_addr, size_of::() as u64) + .map(|value| &mut *(value as *mut T)) } } } @@ -341,10 +339,8 @@ fn translate_type<'a, T>( vm_addr: u64, loader_id: &Pubkey, ) -> Result<&'a T, EbpfError> { - match translate_type_inner::(memory_mapping, AccessType::Load, vm_addr, loader_id) { - Ok(value) => Ok(&*value), - Err(e) => Err(e), - } + translate_type_inner::(memory_mapping, AccessType::Load, vm_addr, loader_id) + .map(|value| &*value) } fn translate_slice_inner<'a, T>( @@ -386,10 +382,8 @@ fn translate_slice<'a, T>( len: u64, loader_id: &Pubkey, ) -> Result<&'a [T], EbpfError> { - match translate_slice_inner::(memory_mapping, AccessType::Load, vm_addr, len, loader_id) { - Ok(value) => Ok(&*value), - Err(e) => Err(e), - } + translate_slice_inner::(memory_mapping, AccessType::Load, vm_addr, len, loader_id) + .map(|value| &*value) } /// Take a virtual pointer to a string (points to BPF VM memory space), translate it diff --git a/runtime/src/message_processor.rs b/runtime/src/message_processor.rs index 66a832c721..335ba189bb 100644 --- a/runtime/src/message_processor.rs +++ b/runtime/src/message_processor.rs @@ -333,7 +333,10 @@ impl<'a> InvokeContext for ThisInvokeContext<'a> { if pre.key == *pubkey { Some(pre.account.clone()) } else { - None + self.pre_accounts + .iter() + .find(|pre| pre.key == *pubkey) + .map(|pre| pre.account.clone()) } }) { return Some(account); diff --git a/sdk/program/src/instruction.rs b/sdk/program/src/instruction.rs index 4852bfe716..2174471e2a 100644 --- a/sdk/program/src/instruction.rs +++ b/sdk/program/src/instruction.rs @@ -241,10 +241,7 @@ impl Instruction { } pub fn checked_add(a: u64, b: u64) -> Result { - match a.checked_add(b) { - Some(sum) => Ok(sum), - None => Err(InstructionError::InsufficientFunds), - } + a.checked_add(b).ok_or(InstructionError::InsufficientFunds) } /// Account metadata used to define Instructions diff --git a/storage-bigtable/src/bigtable.rs b/storage-bigtable/src/bigtable.rs index 1cbf12102d..bc248ba6b7 100644 --- a/storage-bigtable/src/bigtable.rs +++ b/storage-bigtable/src/bigtable.rs @@ -613,10 +613,7 @@ where _ => return Err(err), }, } - match deserialize_bincode_cell_data(row_data, table, key) { - Ok(result) => Ok(CellData::Bincode(result)), - Err(err) => Err(err), - } + deserialize_bincode_cell_data(row_data, table, key).map(CellData::Bincode) } pub(crate) fn deserialize_protobuf_cell_data( diff --git a/storage-proto/src/convert.rs b/storage-proto/src/convert.rs index 9750ab1fee..15a146de32 100644 --- a/storage-proto/src/convert.rs +++ b/storage-proto/src/convert.rs @@ -161,11 +161,7 @@ impl TryFrom for ConfirmedBlock { impl From for generated::ConfirmedTransaction { fn from(value: TransactionWithStatusMeta) -> Self { - let meta = if let Some(meta) = value.meta { - Some(meta.into()) - } else { - None - }; + let meta = value.meta.map(|meta| meta.into()); Self { transaction: Some(value.transaction.into()), meta, @@ -176,11 +172,7 @@ impl From for generated::ConfirmedTransaction { impl TryFrom for TransactionWithStatusMeta { type Error = bincode::Error; fn try_from(value: generated::ConfirmedTransaction) -> std::result::Result { - let meta = if let Some(meta) = value.meta { - Some(meta.try_into()?) - } else { - None - }; + let meta = value.meta.map(|meta| meta.try_into()).transpose()?; Ok(Self { transaction: value.transaction.expect("transaction is required").into(), meta, @@ -762,10 +754,7 @@ impl From for tx_by_addr::TransactionByAddrInfo { Self { signature: >::as_ref(&signature).into(), - err: match err { - None => None, - Some(e) => Some(e.into()), - }, + err: err.map(|e| e.into()), index, memo: memo.map(|memo| tx_by_addr::Memo { memo }), block_time: block_time.map(|timestamp| tx_by_addr::UnixTimestamp { timestamp }), @@ -779,11 +768,10 @@ impl TryFrom for TransactionByAddrInfo { fn try_from( transaction_by_addr: tx_by_addr::TransactionByAddrInfo, ) -> Result { - let err = if let Some(err) = transaction_by_addr.err { - Some(err.try_into()?) - } else { - None - }; + let err = transaction_by_addr + .err + .map(|err| err.try_into()) + .transpose()?; Ok(Self { signature: Signature::new(&transaction_by_addr.signature), diff --git a/tokens/src/arg_parser.rs b/tokens/src/arg_parser.rs index 1cdbe0c74f..5d6604d439 100644 --- a/tokens/src/arg_parser.rs +++ b/tokens/src/arg_parser.rs @@ -410,15 +410,16 @@ fn parse_distribute_stake_args( )?; let lockup_authority_str = value_t!(matches, "lockup_authority", String).ok(); - let lockup_authority = match lockup_authority_str { - Some(path) => Some(signer_from_path( - &signer_matches, - &path, - "lockup authority", - &mut wallet_manager, - )?), - None => None, - }; + let lockup_authority = lockup_authority_str + .map(|path| { + signer_from_path( + &signer_matches, + &path, + "lockup authority", + &mut wallet_manager, + ) + }) + .transpose()?; let stake_args = StakeArgs { stake_account_address,