Skip to content
This repository has been archived by the owner on Jan 13, 2025. It is now read-only.

Commit

Permalink
Simplify some pattern-matches (#16402) (#16446)
Browse files Browse the repository at this point in the history
When those match an exact combinator on Option / Result.

Tool-aided by [comby-rust](https://github.com/huitseeker/comby-rust).

(cherry picked from commit b08cff9)

Co-authored-by: François Garillot <4142+huitseeker@users.noreply.github.com>
  • Loading branch information
mergify[bot] and huitseeker authored Apr 8, 2021
1 parent f7211d3 commit 723e7f1
Show file tree
Hide file tree
Showing 18 changed files with 60 additions and 110 deletions.
3 changes: 1 addition & 2 deletions accounts-cluster-bench/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
24 changes: 6 additions & 18 deletions cli/src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -386,35 +386,26 @@ 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))) =
signer_of(matches, "program_id", wallet_manager)
{
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 =
Expand Down Expand Up @@ -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 =
Expand Down
5 changes: 1 addition & 4 deletions client/src/nonce_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
Expand Down
3 changes: 1 addition & 2 deletions core/src/cluster_slots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
6 changes: 4 additions & 2 deletions core/src/crds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
5 changes: 1 addition & 4 deletions core/src/duplicate_shred.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
18 changes: 8 additions & 10 deletions core/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
7 changes: 4 additions & 3 deletions ledger-tool/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
};

Expand Down
9 changes: 2 additions & 7 deletions ledger/src/blockstore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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()
}
}

Expand Down
4 changes: 1 addition & 3 deletions ledger/src/leader_schedule_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down
3 changes: 1 addition & 2 deletions net-utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
18 changes: 6 additions & 12 deletions programs/bpf_loader/src/syscalls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
}
}
Expand All @@ -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>(
Expand Down Expand Up @@ -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
Expand Down
3 changes: 1 addition & 2 deletions runtime/src/accounts_hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1409,11 +1409,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
Expand Down
7 changes: 4 additions & 3 deletions runtime/src/message_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,10 +383,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| {
Expand Down
5 changes: 1 addition & 4 deletions sdk/program/src/instruction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,10 +267,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
Expand Down
5 changes: 1 addition & 4 deletions storage-bigtable/src/bigtable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>(
Expand Down
26 changes: 7 additions & 19 deletions storage-proto/src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -766,10 +758,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 }),
Expand All @@ -783,11 +772,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),
Expand Down
19 changes: 10 additions & 9 deletions tokens/src/arg_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 723e7f1

Please sign in to comment.