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).
This commit is contained in:
François Garillot
2021-04-08 14:40:37 -04:00
committed by GitHub
parent bb9d2fd07a
commit b08cff9e77
18 changed files with 60 additions and 110 deletions

View File

@ -189,14 +189,13 @@ impl TransactionExecutor {
let mut start = Measure::start("sig_status"); let mut start = Measure::start("sig_status");
let statuses: Vec<_> = sigs_w let statuses: Vec<_> = sigs_w
.chunks(200) .chunks(200)
.map(|sig_chunk| { .flat_map(|sig_chunk| {
let only_sigs: Vec<_> = sig_chunk.iter().map(|s| s.0).collect(); let only_sigs: Vec<_> = sig_chunk.iter().map(|s| s.0).collect();
client client
.get_signature_statuses(&only_sigs) .get_signature_statuses(&only_sigs)
.expect("status fail") .expect("status fail")
.value .value
}) })
.flatten()
.collect(); .collect();
let mut num_cleared = 0; let mut num_cleared = 0;
let start_len = sigs_w.len(); let start_len = sigs_w.len();

View File

@ -386,22 +386,17 @@ pub fn parse_program_subcommand(
default_signer.signer_from_path(matches, wallet_manager)?, default_signer.signer_from_path(matches, wallet_manager)?,
)]; )];
let program_location = if let Some(location) = matches.value_of("program_location") { let program_location = matches
Some(location.to_string()) .value_of("program_location")
} else { .map(|location| location.to_string());
None
};
let buffer_pubkey = if let Ok((buffer_signer, Some(buffer_pubkey))) = let buffer_pubkey = if let Ok((buffer_signer, Some(buffer_pubkey))) =
signer_of(matches, "buffer", wallet_manager) signer_of(matches, "buffer", wallet_manager)
{ {
bulk_signers.push(buffer_signer); bulk_signers.push(buffer_signer);
Some(buffer_pubkey) Some(buffer_pubkey)
} else if let Some(buffer_pubkey) = pubkey_of_signer(matches, "buffer", wallet_manager)?
{
Some(buffer_pubkey)
} else { } else {
None pubkey_of_signer(matches, "buffer", wallet_manager)?
}; };
let program_pubkey = if let Ok((program_signer, Some(program_pubkey))) = 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); bulk_signers.push(program_signer);
Some(program_pubkey) Some(program_pubkey)
} else if let Some(program_pubkey) =
pubkey_of_signer(matches, "program_id", wallet_manager)?
{
Some(program_pubkey)
} else { } else {
None pubkey_of_signer(matches, "program_id", wallet_manager)?
}; };
let upgrade_authority_pubkey = let upgrade_authority_pubkey =
@ -463,11 +454,8 @@ pub fn parse_program_subcommand(
{ {
bulk_signers.push(buffer_signer); bulk_signers.push(buffer_signer);
Some(buffer_pubkey) Some(buffer_pubkey)
} else if let Some(buffer_pubkey) = pubkey_of_signer(matches, "buffer", wallet_manager)?
{
Some(buffer_pubkey)
} else { } else {
None pubkey_of_signer(matches, "buffer", wallet_manager)?
}; };
let buffer_authority_pubkey = let buffer_authority_pubkey =

View File

@ -48,10 +48,7 @@ pub fn get_account_with_commitment(
.value .value
.ok_or_else(|| Error::Client(format!("AccountNotFound: pubkey={}", nonce_pubkey))) .ok_or_else(|| Error::Client(format!("AccountNotFound: pubkey={}", nonce_pubkey)))
}) })
.and_then(|a| match account_identity_ok(&a) { .and_then(|a| account_identity_ok(&a).map(|()| a))
Ok(()) => Ok(a),
Err(e) => Err(e),
})
} }
pub fn account_identity_ok<T: ReadableAccount>(account: &T) -> Result<(), Error> { pub fn account_identity_ok<T: ReadableAccount>(account: &T) -> Result<(), Error> {

View File

@ -191,8 +191,7 @@ impl ClusterSlots {
.read() .read()
.unwrap() .unwrap()
.keys() .keys()
.filter(|x| **x > root) .filter(|x| **x > root && !my_slots.contains(*x))
.filter(|x| !my_slots.contains(*x))
.map(|x| RepairType::HighestShred(*x, 0)) .map(|x| RepairType::HighestShred(*x, 0))
.collect() .collect()
} }

View File

@ -747,8 +747,10 @@ mod test {
let num_epoch_slots = crds let num_epoch_slots = crds
.table .table
.values() .values()
.filter(|value| value.insert_timestamp >= since) .filter(|value| {
.filter(|value| matches!(value.value.data, CrdsData::EpochSlots(_, _))) value.insert_timestamp >= since
&& matches!(value.value.data, CrdsData::EpochSlots(_, _))
})
.count(); .count();
assert_eq!(num_epoch_slots, crds.get_epoch_slots_since(since).count()); assert_eq!(num_epoch_slots, crds.get_epoch_slots_since(since).count());
for value in crds.get_epoch_slots_since(since) { for value in crds.get_epoch_slots_since(since) {

View File

@ -226,10 +226,7 @@ pub fn into_shreds(
chunk_index, chunk_index,
chunk, chunk,
.. ..
} = match chunks.next() { } = chunks.next().ok_or(Error::InvalidDuplicateShreds)?;
None => return Err(Error::InvalidDuplicateShreds),
Some(chunk) => chunk,
};
let slot_leader = leader(slot).ok_or(Error::UnknownSlotLeader)?; let slot_leader = leader(slot).ok_or(Error::UnknownSlotLeader)?;
let check_chunk = check_chunk(slot, shred_index, shred_type, num_chunks); let check_chunk = check_chunk(slot, shred_index, shred_type, num_chunks);
let mut data = HashMap::new(); let mut data = HashMap::new();

View File

@ -3185,16 +3185,14 @@ pub mod rpc_full {
let address = verify_pubkey(address)?; let address = verify_pubkey(address)?;
let config = config.unwrap_or_default(); let config = config.unwrap_or_default();
let before = if let Some(before) = config.before { let before = config
Some(verify_signature(&before)?) .before
} else { .map(|ref before| verify_signature(before))
None .transpose()?;
}; let until = config
let until = if let Some(until) = config.until { .until
Some(verify_signature(&until)?) .map(|ref until| verify_signature(until))
} else { .transpose()?;
None
};
let limit = config let limit = config
.limit .limit
.unwrap_or(MAX_GET_CONFIRMED_SIGNATURES_FOR_ADDRESS2_LIMIT); .unwrap_or(MAX_GET_CONFIRMED_SIGNATURES_FOR_ADDRESS2_LIMIT);

View File

@ -1661,10 +1661,11 @@ fn main() {
let parse_results = { let parse_results = {
if let Some(slot_string) = frozen_regex.captures_iter(&line).next() { if let Some(slot_string) = frozen_regex.captures_iter(&line).next() {
Some((slot_string, &mut frozen)) Some((slot_string, &mut frozen))
} else if let Some(slot_string) = full_regex.captures_iter(&line).next() {
Some((slot_string, &mut full))
} else { } else {
None full_regex
.captures_iter(&line)
.next()
.map(|slot_string| (slot_string, &mut full))
} }
}; };

View File

@ -2424,10 +2424,7 @@ impl Blockstore {
for (slot, signature) in address_signatures.into_iter() { for (slot, signature) in address_signatures.into_iter() {
let transaction_status = let transaction_status =
self.get_transaction_status(signature, &confirmed_unrooted_slots)?; self.get_transaction_status(signature, &confirmed_unrooted_slots)?;
let err = match transaction_status { let err = transaction_status.and_then(|(_slot, status)| status.status.err());
None => None,
Some((_slot, status)) => status.status.err(),
};
let block_time = self.get_block_time(slot)?; let block_time = self.get_block_time(slot)?;
infos.push(ConfirmedTransactionStatusWithSignature { infos.push(ConfirmedTransactionStatusWithSignature {
signature, signature,
@ -3185,10 +3182,8 @@ fn find_slot_meta_in_cached_state<'a>(
) -> Option<Rc<RefCell<SlotMeta>>> { ) -> Option<Rc<RefCell<SlotMeta>>> {
if let Some(entry) = working_set.get(&slot) { if let Some(entry) = working_set.get(&slot) {
Some(entry.new_slot_meta.clone()) Some(entry.new_slot_meta.clone())
} else if let Some(entry) = chained_slots.get(&slot) {
Some(entry.clone())
} else { } else {
None chained_slots.get(&slot).cloned()
} }
} }

View File

@ -212,10 +212,8 @@ impl LeaderScheduleCache {
let epoch_schedule = self.get_epoch_leader_schedule(epoch); let epoch_schedule = self.get_epoch_leader_schedule(epoch);
if epoch_schedule.is_some() { if epoch_schedule.is_some() {
epoch_schedule epoch_schedule
} else if let Some(epoch_schedule) = self.compute_epoch_schedule(epoch, bank) {
Some(epoch_schedule)
} else { } else {
None self.compute_epoch_schedule(epoch, bank)
} }
} }

View File

@ -198,8 +198,7 @@ fn do_verify_reachable_ports(
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
checked_ports_and_sockets checked_ports_and_sockets
.iter() .iter()
.map(|(_, sockets)| sockets) .flat_map(|(_, sockets)| sockets),
.flatten(),
); );
let _ = ip_echo_server_request( let _ = ip_echo_server_request(

View File

@ -297,10 +297,8 @@ fn translate_type_inner<'a, T>(
Err(SyscallError::UnalignedPointer.into()) Err(SyscallError::UnalignedPointer.into())
} else { } else {
unsafe { unsafe {
match translate(memory_mapping, access_type, vm_addr, size_of::<T>() as u64) { translate(memory_mapping, access_type, vm_addr, size_of::<T>() as u64)
Ok(value) => Ok(&mut *(value as *mut T)), .map(|value| &mut *(value as *mut T))
Err(e) => Err(e),
}
} }
} }
} }
@ -316,10 +314,8 @@ fn translate_type<'a, T>(
vm_addr: u64, vm_addr: u64,
loader_id: &Pubkey, loader_id: &Pubkey,
) -> Result<&'a T, EbpfError<BpfError>> { ) -> Result<&'a T, EbpfError<BpfError>> {
match translate_type_inner::<T>(memory_mapping, AccessType::Load, vm_addr, loader_id) { translate_type_inner::<T>(memory_mapping, AccessType::Load, vm_addr, loader_id)
Ok(value) => Ok(&*value), .map(|value| &*value)
Err(e) => Err(e),
}
} }
fn translate_slice_inner<'a, T>( fn translate_slice_inner<'a, T>(
@ -361,10 +357,8 @@ fn translate_slice<'a, T>(
len: u64, len: u64,
loader_id: &Pubkey, loader_id: &Pubkey,
) -> Result<&'a [T], EbpfError<BpfError>> { ) -> Result<&'a [T], EbpfError<BpfError>> {
match translate_slice_inner::<T>(memory_mapping, AccessType::Load, vm_addr, len, loader_id) { translate_slice_inner::<T>(memory_mapping, AccessType::Load, vm_addr, len, loader_id)
Ok(value) => Ok(&*value), .map(|value| &*value)
Err(e) => Err(e),
}
} }
/// Take a virtual pointer to a string (points to BPF VM memory space), translate it /// Take a virtual pointer to a string (points to BPF VM memory space), translate it

View File

@ -1861,11 +1861,10 @@ pub mod tests {
// handle fanout^x -1, +0, +1 for a few 'x's // handle fanout^x -1, +0, +1 for a few 'x's
const FANOUT: usize = 3; const FANOUT: usize = 3;
let mut hash_counts: Vec<_> = (1..6) let mut hash_counts: Vec<_> = (1..6)
.map(|x| { .flat_map(|x| {
let mark = FANOUT.pow(x); let mark = FANOUT.pow(x);
vec![mark - 1, mark, mark + 1] vec![mark - 1, mark, mark + 1]
}) })
.flatten()
.collect(); .collect();
// saturate the test space for threshold to threshold + target // saturate the test space for threshold to threshold + target

View File

@ -379,10 +379,11 @@ impl<'a> InvokeContext for ThisInvokeContext<'a> {
self.account_deps.iter().find(|(key, _)| key == pubkey) self.account_deps.iter().find(|(key, _)| key == pubkey)
{ {
Some(account.clone()) Some(account.clone())
} else if let Some(pre) = self.pre_accounts.iter().find(|pre| pre.key == *pubkey) {
Some(pre.account.clone())
} else { } else {
None self.pre_accounts
.iter()
.find(|pre| pre.key == *pubkey)
.map(|pre| pre.account.clone())
} }
} else { } else {
if let Some(account) = self.pre_accounts.iter().find_map(|pre| { if let Some(account) = self.pre_accounts.iter().find_map(|pre| {

View File

@ -272,10 +272,7 @@ impl Instruction {
} }
pub fn checked_add(a: u64, b: u64) -> Result<u64, InstructionError> { pub fn checked_add(a: u64, b: u64) -> Result<u64, InstructionError> {
match a.checked_add(b) { a.checked_add(b).ok_or(InstructionError::InsufficientFunds)
Some(sum) => Ok(sum),
None => Err(InstructionError::InsufficientFunds),
}
} }
/// Account metadata used to define Instructions /// Account metadata used to define Instructions

View File

@ -611,10 +611,7 @@ where
_ => return Err(err), _ => return Err(err),
}, },
} }
match deserialize_bincode_cell_data(row_data, table, key) { deserialize_bincode_cell_data(row_data, table, key).map(CellData::Bincode)
Ok(result) => Ok(CellData::Bincode(result)),
Err(err) => Err(err),
}
} }
pub(crate) fn deserialize_protobuf_cell_data<T>( pub(crate) fn deserialize_protobuf_cell_data<T>(

View File

@ -161,11 +161,7 @@ impl TryFrom<generated::ConfirmedBlock> for ConfirmedBlock {
impl From<TransactionWithStatusMeta> for generated::ConfirmedTransaction { impl From<TransactionWithStatusMeta> for generated::ConfirmedTransaction {
fn from(value: TransactionWithStatusMeta) -> Self { fn from(value: TransactionWithStatusMeta) -> Self {
let meta = if let Some(meta) = value.meta { let meta = value.meta.map(|meta| meta.into());
Some(meta.into())
} else {
None
};
Self { Self {
transaction: Some(value.transaction.into()), transaction: Some(value.transaction.into()),
meta, meta,
@ -176,11 +172,7 @@ impl From<TransactionWithStatusMeta> for generated::ConfirmedTransaction {
impl TryFrom<generated::ConfirmedTransaction> for TransactionWithStatusMeta { impl TryFrom<generated::ConfirmedTransaction> for TransactionWithStatusMeta {
type Error = bincode::Error; type Error = bincode::Error;
fn try_from(value: generated::ConfirmedTransaction) -> std::result::Result<Self, Self::Error> { fn try_from(value: generated::ConfirmedTransaction) -> std::result::Result<Self, Self::Error> {
let meta = if let Some(meta) = value.meta { let meta = value.meta.map(|meta| meta.try_into()).transpose()?;
Some(meta.try_into()?)
} else {
None
};
Ok(Self { Ok(Self {
transaction: value.transaction.expect("transaction is required").into(), transaction: value.transaction.expect("transaction is required").into(),
meta, meta,
@ -770,10 +762,7 @@ impl From<TransactionByAddrInfo> for tx_by_addr::TransactionByAddrInfo {
Self { Self {
signature: <Signature as AsRef<[u8]>>::as_ref(&signature).into(), signature: <Signature as AsRef<[u8]>>::as_ref(&signature).into(),
err: match err { err: err.map(|e| e.into()),
None => None,
Some(e) => Some(e.into()),
},
index, index,
memo: memo.map(|memo| tx_by_addr::Memo { memo }), memo: memo.map(|memo| tx_by_addr::Memo { memo }),
block_time: block_time.map(|timestamp| tx_by_addr::UnixTimestamp { timestamp }), block_time: block_time.map(|timestamp| tx_by_addr::UnixTimestamp { timestamp }),
@ -787,11 +776,10 @@ impl TryFrom<tx_by_addr::TransactionByAddrInfo> for TransactionByAddrInfo {
fn try_from( fn try_from(
transaction_by_addr: tx_by_addr::TransactionByAddrInfo, transaction_by_addr: tx_by_addr::TransactionByAddrInfo,
) -> Result<Self, Self::Error> { ) -> Result<Self, Self::Error> {
let err = if let Some(err) = transaction_by_addr.err { let err = transaction_by_addr
Some(err.try_into()?) .err
} else { .map(|err| err.try_into())
None .transpose()?;
};
Ok(Self { Ok(Self {
signature: Signature::new(&transaction_by_addr.signature), signature: Signature::new(&transaction_by_addr.signature),

View File

@ -410,15 +410,16 @@ fn parse_distribute_stake_args(
)?; )?;
let lockup_authority_str = value_t!(matches, "lockup_authority", String).ok(); let lockup_authority_str = value_t!(matches, "lockup_authority", String).ok();
let lockup_authority = match lockup_authority_str { let lockup_authority = lockup_authority_str
Some(path) => Some(signer_from_path( .map(|path| {
&signer_matches, signer_from_path(
&path, &signer_matches,
"lockup authority", &path,
&mut wallet_manager, "lockup authority",
)?), &mut wallet_manager,
None => None, )
}; })
.transpose()?;
let stake_args = StakeArgs { let stake_args = StakeArgs {
stake_account_address, stake_account_address,