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
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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 statuses: Vec<_> = sigs_w
.chunks(200)
.map(|sig_chunk| {
.flat_map(|sig_chunk| {
let only_sigs: Vec<_> = sig_chunk.iter().map(|s| s.0).collect();
client
.get_signature_statuses(&only_sigs)
.expect("status fail")
.value
})
.flatten()
.collect();
let mut num_cleared = 0;
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)?,
)];
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 =

View File

@ -48,10 +48,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<T: ReadableAccount>(account: &T) -> Result<(), Error> {

View File

@ -191,8 +191,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()
}

View File

@ -747,8 +747,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) {

View File

@ -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();

View File

@ -3185,16 +3185,14 @@ pub mod rpc_full {
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);

View File

@ -1661,10 +1661,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))
}
};

View File

@ -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,
@ -3185,10 +3182,8 @@ fn find_slot_meta_in_cached_state<'a>(
) -> Option<Rc<RefCell<SlotMeta>>> {
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()
}
}

View File

@ -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)
}
}

View File

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

View File

@ -297,10 +297,8 @@ fn translate_type_inner<'a, T>(
Err(SyscallError::UnalignedPointer.into())
} else {
unsafe {
match translate(memory_mapping, access_type, vm_addr, size_of::<T>() as u64) {
Ok(value) => Ok(&mut *(value as *mut T)),
Err(e) => Err(e),
}
translate(memory_mapping, access_type, vm_addr, size_of::<T>() as u64)
.map(|value| &mut *(value as *mut T))
}
}
}
@ -316,10 +314,8 @@ fn translate_type<'a, T>(
vm_addr: u64,
loader_id: &Pubkey,
) -> Result<&'a T, EbpfError<BpfError>> {
match translate_type_inner::<T>(memory_mapping, AccessType::Load, vm_addr, loader_id) {
Ok(value) => Ok(&*value),
Err(e) => Err(e),
}
translate_type_inner::<T>(memory_mapping, AccessType::Load, vm_addr, loader_id)
.map(|value| &*value)
}
fn translate_slice_inner<'a, T>(
@ -361,10 +357,8 @@ fn translate_slice<'a, T>(
len: u64,
loader_id: &Pubkey,
) -> Result<&'a [T], EbpfError<BpfError>> {
match translate_slice_inner::<T>(memory_mapping, AccessType::Load, vm_addr, len, loader_id) {
Ok(value) => Ok(&*value),
Err(e) => Err(e),
}
translate_slice_inner::<T>(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

View File

@ -1861,11 +1861,10 @@ pub mod tests {
// handle fanout^x -1, +0, +1 for a few 'x's
const FANOUT: usize = 3;
let mut hash_counts: Vec<_> = (1..6)
.map(|x| {
.flat_map(|x| {
let mark = FANOUT.pow(x);
vec![mark - 1, mark, mark + 1]
})
.flatten()
.collect();
// 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)
{
Some(account.clone())
} else if let Some(pre) = self.pre_accounts.iter().find(|pre| pre.key == *pubkey) {
Some(pre.account.clone())
} else {
None
self.pre_accounts
.iter()
.find(|pre| pre.key == *pubkey)
.map(|pre| pre.account.clone())
}
} else {
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> {
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

View File

@ -611,10 +611,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<T>(

View File

@ -161,11 +161,7 @@ impl TryFrom<generated::ConfirmedBlock> for ConfirmedBlock {
impl From<TransactionWithStatusMeta> 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<TransactionWithStatusMeta> for generated::ConfirmedTransaction {
impl TryFrom<generated::ConfirmedTransaction> for TransactionWithStatusMeta {
type Error = bincode::Error;
fn try_from(value: generated::ConfirmedTransaction) -> std::result::Result<Self, Self::Error> {
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,
@ -770,10 +762,7 @@ impl From<TransactionByAddrInfo> for tx_by_addr::TransactionByAddrInfo {
Self {
signature: <Signature as AsRef<[u8]>>::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 }),
@ -787,11 +776,10 @@ impl TryFrom<tx_by_addr::TransactionByAddrInfo> for TransactionByAddrInfo {
fn try_from(
transaction_by_addr: tx_by_addr::TransactionByAddrInfo,
) -> Result<Self, Self::Error> {
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),

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 = 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,