removes instances of clippy::manual_let_else (#32417)

This commit is contained in:
behzad nouri 2023-07-09 21:41:36 +00:00 committed by GitHub
parent 8dfb956719
commit d54b6204be
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
46 changed files with 261 additions and 414 deletions

View File

@ -733,14 +733,11 @@ impl<'b, T: Clone + Copy + 'static> Bucket<T> {
pub fn insert(&mut self, key: &Pubkey, value: (&[T], RefCount)) {
let (new, refct) = value;
loop {
let rv = self.try_write(key, new.iter(), new.len(), refct);
match rv {
Ok(_) => return,
Err(err) => {
self.grow(err);
self.handle_delayed_grows();
}
}
let Err(err) = self.try_write(key, new.iter(), new.len(), refct) else {
return;
};
self.grow(err);
self.handle_delayed_grows();
}
}

View File

@ -90,6 +90,7 @@ _ scripts/cargo-for-all-lock-files.sh -- "+${rust_nightly}" clippy --workspace -
--deny=warnings \
--deny=clippy::default_trait_access \
--deny=clippy::integer_arithmetic \
--deny=clippy::manual_let_else \
--deny=clippy::used_underscore_binding \
"${nightly_clippy_allows[@]}"
@ -103,6 +104,7 @@ _ scripts/cargo-for-all-lock-files.sh -- clippy --workspace --tests --bins --ex
--deny=warnings \
--deny=clippy::default_trait_access \
--deny=clippy::integer_arithmetic \
--deny=clippy::manual_let_else \
--deny=clippy::used_underscore_binding
if [[ -n $CI ]]; then

View File

@ -447,17 +447,14 @@ impl ClusterInfoVoteListener {
verified_packets_sender: &BankingPacketSender,
verified_vote_packets: &VerifiedVotePackets,
) -> Result<()> {
let current_working_bank = match current_working_bank {
Some(current_working_bank) => current_working_bank,
None => {
// We are not the leader!
if let Some(bank_vote_sender_state) = bank_vote_sender_state_option {
// This ensures we report the last slot's metrics
bank_vote_sender_state.report_metrics();
*bank_vote_sender_state_option = None;
}
return Ok(());
let Some(current_working_bank) = current_working_bank else {
// We are not the leader!
if let Some(bank_vote_sender_state) = bank_vote_sender_state_option {
// This ensures we report the last slot's metrics
bank_vote_sender_state.report_metrics();
*bank_vote_sender_state_option = None;
}
return Ok(());
};
// We will take this lock at most once every `BANK_SEND_VOTES_LOOP_SLEEP_MS`
if let Some(bank_vote_sender_state) = bank_vote_sender_state_option {

View File

@ -186,9 +186,8 @@ impl ClusterSlots {
})
.collect()
};
let slot_peers = match self.lookup(slot) {
None => return stakes,
Some(slot_peers) => slot_peers,
let Some(slot_peers) = self.lookup(slot) else {
return stakes;
};
let slot_peers = slot_peers.read().unwrap();
repair_peers

View File

@ -746,9 +746,8 @@ impl Tower {
latest_validator_votes_for_frozen_banks: &LatestValidatorVotesForFrozenBanks,
heaviest_subtree_fork_choice: &HeaviestSubtreeForkChoice,
) -> SwitchForkDecision {
let (last_voted_slot, last_voted_hash) = match self.last_voted_slot_hash() {
None => return SwitchForkDecision::SameFork,
Some(slot_hash) => slot_hash,
let Some((last_voted_slot, last_voted_hash)) = self.last_voted_slot_hash() else {
return SwitchForkDecision::SameFork;
};
let root = self.root();
let empty_ancestors = HashSet::default();

View File

@ -358,31 +358,22 @@ impl AncestorHashesService {
ancestor_socket: &UdpSocket,
) -> Option<AncestorRequestDecision> {
let from_addr = packet.meta().socket_addr();
let packet_data = match packet.data(..) {
Some(data) => data,
None => {
stats.invalid_packets += 1;
return None;
}
let Some(packet_data) = packet.data(..) else {
stats.invalid_packets += 1;
return None;
};
let mut cursor = Cursor::new(packet_data);
let response = match deserialize_from_with_limit(&mut cursor) {
Ok(response) => response,
Err(_) => {
stats.invalid_packets += 1;
return None;
}
let Ok(response) = deserialize_from_with_limit(&mut cursor) else {
stats.invalid_packets += 1;
return None;
};
match response {
AncestorHashesResponse::Hashes(ref hashes) => {
// deserialize trailing nonce
let nonce = match deserialize_from_with_limit(&mut cursor) {
Ok(nonce) => nonce,
Err(_) => {
stats.invalid_packets += 1;
return None;
}
let Ok(nonce) = deserialize_from_with_limit(&mut cursor) else {
stats.invalid_packets += 1;
return None;
};
// verify that packet does not contain extraneous data

View File

@ -884,10 +884,9 @@ pub mod tests {
// We don't have the earlier ancestors because we just started up, however sample should
// not be rejected as invalid.
let DuplicateAncestorDecision::EarliestMismatchFound(repair_status) = run_add_multiple_correct_and_incorrect_responses(
vec![],
&mut test_setup,
) else {
let DuplicateAncestorDecision::EarliestMismatchFound(repair_status) =
run_add_multiple_correct_and_incorrect_responses(vec![], &mut test_setup)
else {
panic!("Incorrect decision")
};
assert_eq!(
@ -938,10 +937,12 @@ pub mod tests {
)];
// We have no entries in the blockstore, so all the ancestors will be missing
let DuplicateAncestorDecision::EarliestMismatchFound(repair_status) = run_add_multiple_correct_and_incorrect_responses(
desired_incorrect_responses,
&mut test_setup,
) else {
let DuplicateAncestorDecision::EarliestMismatchFound(repair_status) =
run_add_multiple_correct_and_incorrect_responses(
desired_incorrect_responses,
&mut test_setup,
)
else {
panic!("Incorrect decision")
};
assert_eq!(
@ -1089,10 +1090,9 @@ pub mod tests {
}
// All the ancestors matched, only the requested slot should be dumped
let DuplicateAncestorDecision::EarliestMismatchFound(repair_status) = run_add_multiple_correct_and_incorrect_responses(
vec![],
&mut test_setup,
) else {
let DuplicateAncestorDecision::EarliestMismatchFound(repair_status) =
run_add_multiple_correct_and_incorrect_responses(vec![], &mut test_setup)
else {
panic!("Incorrect decision")
};
assert_eq!(
@ -1133,10 +1133,9 @@ pub mod tests {
.add_tree(tree, true, true, 2, Hash::default());
// All the ancestors matched, only the requested slot should be dumped
let DuplicateAncestorDecision::EarliestPrunedMismatchFound(repair_status) = run_add_multiple_correct_and_incorrect_responses(
vec![],
&mut test_setup,
) else {
let DuplicateAncestorDecision::EarliestPrunedMismatchFound(repair_status) =
run_add_multiple_correct_and_incorrect_responses(vec![], &mut test_setup)
else {
panic!("Incorrect decision")
};
assert_eq!(

View File

@ -867,25 +867,19 @@ impl ServeRepair {
if u128::from(time_diff_ms) > SIGNED_REPAIR_TIME_WINDOW.as_millis() {
return Err(Error::from(RepairVerifyError::TimeSkew));
}
let leading_buf = match packet.data(..4) {
Some(buf) => buf,
None => {
debug_assert!(
false,
"request should have failed deserialization: {request:?}",
);
return Err(Error::from(RepairVerifyError::Malformed));
}
let Some(leading_buf) = packet.data(..4) else {
debug_assert!(
false,
"request should have failed deserialization: {request:?}",
);
return Err(Error::from(RepairVerifyError::Malformed));
};
let trailing_buf = match packet.data(4 + SIGNATURE_BYTES..) {
Some(buf) => buf,
None => {
debug_assert!(
false,
"request should have failed deserialization: {request:?}",
);
return Err(Error::from(RepairVerifyError::Malformed));
}
let Some(trailing_buf) = packet.data(4 + SIGNATURE_BYTES..) else {
debug_assert!(
false,
"request should have failed deserialization: {request:?}",
);
return Err(Error::from(RepairVerifyError::Malformed));
};
let from_id = request.sender();
let signed_data = [leading_buf, trailing_buf].concat();
@ -978,11 +972,10 @@ impl ServeRepair {
}
}
stats.processed += 1;
let rsp = match Self::handle_repair(
recycler, &from_addr, blockstore, request, stats, ping_cache,
) {
None => continue,
Some(rsp) => rsp,
let Some(rsp) =
Self::handle_repair(recycler, &from_addr, blockstore, request, stats, ping_cache)
else {
continue;
};
let num_response_packets = rsp.len();
let num_response_bytes = rsp.iter().map(|p| p.meta().size).sum();

View File

@ -2272,17 +2272,14 @@ impl ReplayStage {
return None;
}
let authorized_voter_pubkey =
if let Some(authorized_voter_pubkey) = vote_state.get_authorized_voter(bank.epoch()) {
authorized_voter_pubkey
} else {
warn!(
"Vote account {} has no authorized voter for epoch {}. Unable to vote",
vote_account_pubkey,
bank.epoch()
);
return None;
};
let Some(authorized_voter_pubkey) = vote_state.get_authorized_voter(bank.epoch()) else {
warn!(
"Vote account {} has no authorized voter for epoch {}. Unable to vote",
vote_account_pubkey,
bank.epoch()
);
return None;
};
let authorized_voter_keypair = match authorized_voter_keypairs
.iter()

View File

@ -782,9 +782,8 @@ impl EntrySlice for [Entry] {
recyclers: VerifyRecyclers,
) -> EntryVerificationState {
let start = Instant::now();
let api = match perf_libs::api() {
None => return self.verify_cpu(start_hash),
Some(api) => api,
let Some(api) = perf_libs::api() else {
return self.verify_cpu(start_hash);
};
inc_new_counter_info!("entry_verify-num_entries", self.len());

View File

@ -531,9 +531,8 @@ fn main() -> Result<(), Box<dyn error::Error>> {
let mut bootstrap_validator_pubkeys_iter = bootstrap_validator_pubkeys.iter();
loop {
let identity_pubkey = match bootstrap_validator_pubkeys_iter.next() {
None => break,
Some(identity_pubkey) => identity_pubkey,
let Some(identity_pubkey) = bootstrap_validator_pubkeys_iter.next() else {
break;
};
let vote_pubkey = bootstrap_validator_pubkeys_iter.next().unwrap();
let stake_pubkey = bootstrap_validator_pubkeys_iter.next().unwrap();

View File

@ -1412,9 +1412,8 @@ impl ClusterInfo {
const THROTTLE_DELAY: u64 = CRDS_GOSSIP_PULL_CRDS_TIMEOUT_MS / 2;
let entrypoint = {
let mut entrypoints = self.entrypoints.write().unwrap();
let entrypoint = match entrypoints.choose_mut(&mut rand::thread_rng()) {
Some(entrypoint) => entrypoint,
None => return,
let Some(entrypoint) = entrypoints.choose_mut(&mut rand::thread_rng()) else {
return;
};
if !pulls.is_empty() {
let now = timestamp();

View File

@ -428,13 +428,11 @@ impl TryFrom<ContactInfoLite> for ContactInfo {
let mut port = 0u16;
for &SocketEntry { key, index, offset } in &node.sockets {
port += offset;
let entry = match node.cache.get_mut(usize::from(key)) {
None => continue,
Some(entry) => entry,
let Some(entry) = node.cache.get_mut(usize::from(key)) else {
continue;
};
let addr = match node.addrs.get(usize::from(index)) {
None => continue,
Some(&addr) => addr,
let Some(&addr) = node.addrs.get(usize::from(index)) else {
continue;
};
let socket = SocketAddr::new(addr, port);
if sanitize_socket(&socket).is_ok() {

View File

@ -518,9 +518,8 @@ impl Crds {
}
pub fn remove(&mut self, key: &CrdsValueLabel, now: u64) {
let (index, _ /*label*/, value) = match self.table.swap_remove_full(key) {
Some(entry) => entry,
None => return,
let Some((index, _ /*label*/, value)) = self.table.swap_remove_full(key) else {
return;
};
self.purged.push_back((value.value_hash, now));
self.shards.remove(index, &value);

View File

@ -405,9 +405,8 @@ pub(crate) fn maybe_ping_gossip_addresses<R: Rng + CryptoRng>(
nodes
.into_iter()
.filter(|node| {
let node_gossip = match node.gossip() {
Err(_) => return false,
Ok(addr) => addr,
let Ok(node_gossip) = node.gossip() else {
return false;
};
let (check, ping) = {
let node = (*node.pubkey(), node_gossip);

View File

@ -462,9 +462,8 @@ impl NodeInstance {
// the same owner. Otherwise returns true if self has more recent timestamp
// than other, and so overrides it.
pub(crate) fn overrides(&self, other: &CrdsValue) -> Option<bool> {
let other = match &other.data {
CrdsData::NodeInstance(other) => other,
_ => return None,
let CrdsData::NodeInstance(other) = &other.data else {
return None;
};
if self.token == other.token || self.from != other.from {
return None;

View File

@ -3016,10 +3016,9 @@ fn main() {
let mut bootstrap_validator_pubkeys_iter =
bootstrap_validator_pubkeys.iter();
loop {
let identity_pubkey = match bootstrap_validator_pubkeys_iter.next()
{
None => break,
Some(identity_pubkey) => identity_pubkey,
let Some(identity_pubkey) = bootstrap_validator_pubkeys_iter.next()
else {
break;
};
let vote_pubkey = bootstrap_validator_pubkeys_iter.next().unwrap();
let stake_pubkey = bootstrap_validator_pubkeys_iter.next().unwrap();

View File

@ -1966,12 +1966,9 @@ impl Blockstore {
require_previous_blockhash: bool,
) -> Result<VersionedConfirmedBlock> {
let slot_meta_cf = self.db.column::<cf::SlotMeta>();
let slot_meta = match slot_meta_cf.get(slot)? {
Some(slot_meta) => slot_meta,
None => {
info!("SlotMeta not found for slot {}", slot);
return Err(BlockstoreError::SlotUnavailable);
}
let Some(slot_meta) = slot_meta_cf.get(slot)? else {
info!("SlotMeta not found for slot {}", slot);
return Err(BlockstoreError::SlotUnavailable);
};
if slot_meta.is_full() {
let slot_entries = self.get_slot_entries(slot, 0)?;

View File

@ -345,9 +345,8 @@ impl ErasureMeta {
// Returns true if the erasure fields on the shred
// are consistent with the erasure-meta.
pub(crate) fn check_coding_shred(&self, shred: &Shred) -> bool {
let mut other = match Self::from_coding_shred(shred) {
Some(erasure_meta) => erasure_meta,
None => return false,
let Some(mut other) = Self::from_coding_shred(shred) else {
return false;
};
other.__unused_size = self.__unused_size;
self == &other

View File

@ -586,9 +586,8 @@ pub mod layout {
}
pub(super) fn get_shred_variant(shred: &[u8]) -> Result<ShredVariant, Error> {
let shred_variant = match shred.get(OFFSET_OF_SHRED_VARIANT) {
None => return Err(Error::InvalidPayloadSize(shred.len())),
Some(shred_variant) => *shred_variant,
let Some(&shred_variant) = shred.get(OFFSET_OF_SHRED_VARIANT) else {
return Err(Error::InvalidPayloadSize(shred.len()));
};
ShredVariant::try_from(shred_variant).map_err(|_| Error::InvalidShredVariant)
}
@ -673,9 +672,8 @@ pub mod layout {
if get_shred_type(shred)? != ShredType::Data {
return Err(Error::InvalidShredType);
}
let flags = match shred.get(85) {
None => return Err(Error::InvalidPayloadSize(shred.len())),
Some(flags) => flags,
let Some(flags) = shred.get(85) else {
return Err(Error::InvalidPayloadSize(shred.len()));
};
Ok(flags & ShredFlags::SHRED_TICK_REFERENCE_MASK.bits())
}
@ -915,12 +913,9 @@ pub fn should_discard_shred(
}
}
}
let shred_variant = match layout::get_shred_variant(shred) {
Ok(shred_variant) => shred_variant,
Err(_) => {
stats.bad_shred_type += 1;
return true;
}
let Ok(shred_variant) = layout::get_shred_variant(shred) else {
stats.bad_shred_type += 1;
return true;
};
let slot = match layout::get_slot(shred) {
Some(slot) => {
@ -935,12 +930,9 @@ pub fn should_discard_shred(
return true;
}
};
let index = match layout::get_index(shred) {
Some(index) => index,
None => {
stats.index_bad_deserialize += 1;
return true;
}
let Some(index) = layout::get_index(shred) else {
stats.index_bad_deserialize += 1;
return true;
};
match ShredType::from(shred_variant) {
ShredType::Code => {
@ -958,19 +950,13 @@ pub fn should_discard_shred(
stats.index_out_of_bounds += 1;
return true;
}
let parent_offset = match layout::get_parent_offset(shred) {
Some(parent_offset) => parent_offset,
None => {
stats.bad_parent_offset += 1;
return true;
}
let Some(parent_offset) = layout::get_parent_offset(shred) else {
stats.bad_parent_offset += 1;
return true;
};
let parent = match slot.checked_sub(Slot::from(parent_offset)) {
Some(parent) => parent,
None => {
stats.bad_parent_offset += 1;
return true;
}
let Some(parent) = slot.checked_sub(Slot::from(parent_offset)) else {
stats.bad_parent_offset += 1;
return true;
};
if !blockstore::verify_shred_slots(slot, parent, root) {
stats.slot_out_of_range += 1;

View File

@ -186,9 +186,8 @@ impl ShredData {
// Deserialize headers.
let mut cursor = Cursor::new(&shard[..]);
let common_header: ShredCommonHeader = deserialize_from_with_limit(&mut cursor)?;
let proof_size = match common_header.shred_variant {
ShredVariant::MerkleData(proof_size) => proof_size,
_ => return Err(Error::InvalidShredVariant),
let ShredVariant::MerkleData(proof_size) = common_header.shred_variant else {
return Err(Error::InvalidShredVariant);
};
if ShredCode::capacity(proof_size)? != shard_size {
return Err(Error::InvalidShardSize(shard_size));
@ -293,9 +292,8 @@ impl ShredCode {
coding_header: CodingShredHeader,
mut shard: Vec<u8>,
) -> Result<Self, Error> {
let proof_size = match common_header.shred_variant {
ShredVariant::MerkleCode(proof_size) => proof_size,
_ => return Err(Error::InvalidShredVariant),
let ShredVariant::MerkleCode(proof_size) = common_header.shred_variant else {
return Err(Error::InvalidShredVariant);
};
let shard_size = shard.len();
if Self::capacity(proof_size)? != shard_size {
@ -630,9 +628,8 @@ pub(super) fn recover(
) -> Result<Vec<Shred>, Error> {
// Grab {common, coding} headers from first coding shred.
let headers = shreds.iter().find_map(|shred| {
let shred = match shred {
Shred::ShredCode(shred) => shred,
Shred::ShredData(_) => return None,
let Shred::ShredCode(shred) = shred else {
return None;
};
let position = u32::from(shred.coding_header.position);
let common_header = ShredCommonHeader {

View File

@ -34,27 +34,22 @@ pub fn verify_shred_cpu(
if packet.meta().discard() {
return false;
}
let shred = match shred::layout::get_shred(packet) {
None => return false,
Some(shred) => shred,
let Some(shred) = shred::layout::get_shred(packet) else {
return false;
};
let slot = match shred::layout::get_slot(shred) {
None => return false,
Some(slot) => slot,
let Some(slot) = shred::layout::get_slot(shred) else {
return false;
};
trace!("slot {}", slot);
let pubkey = match slot_leaders.get(&slot) {
None => return false,
Some(pubkey) => pubkey,
let Some(pubkey) = slot_leaders.get(&slot) else {
return false;
};
let signature = match shred::layout::get_signature(shred) {
None => return false,
Some(signature) => signature,
let Some(signature) = shred::layout::get_signature(shred) else {
return false;
};
trace!("signature {}", signature);
let data = match shred::layout::get_signed_data(shred) {
None => return false,
Some(data) => data,
let Some(data) = shred::layout::get_signed_data(shred) else {
return false;
};
signature.verify(pubkey, data.as_ref())
}
@ -255,9 +250,8 @@ pub fn verify_shreds_gpu(
slot_leaders: &HashMap<Slot, /*pubkey:*/ [u8; 32]>,
recycler_cache: &RecyclerCache,
) -> Vec<Vec<u8>> {
let api = match perf_libs::api() {
None => return verify_shreds_cpu(thread_pool, batches, slot_leaders),
Some(api) => api,
let Some(api) = perf_libs::api() else {
return verify_shreds_cpu(thread_pool, batches, slot_leaders);
};
let (pubkeys, pubkey_offsets) =
slot_key_data_for_gpu(thread_pool, batches, slot_leaders, recycler_cache);
@ -378,9 +372,8 @@ pub fn sign_shreds_gpu(
if packet_count < SIGN_SHRED_GPU_MIN || pinned_keypair.is_none() {
return sign_shreds_cpu(thread_pool, keypair, batches);
}
let api = match perf_libs::api() {
None => return sign_shreds_cpu(thread_pool, keypair, batches),
Some(api) => api,
let Some(api) = perf_libs::api() else {
return sign_shreds_cpu(thread_pool, keypair, batches);
};
let pinned_keypair = pinned_keypair.as_ref().unwrap();

View File

@ -131,21 +131,17 @@ fn verify_packet(packet: &mut Packet, reject_non_vote: bool) -> bool {
for _ in 0..packet_offsets.sig_len {
let pubkey_end = pubkey_start.saturating_add(size_of::<Pubkey>());
let sig_end = match sig_start.checked_add(size_of::<Signature>()) {
Some(sig_end) => sig_end,
None => return false,
let Some(sig_end) = sig_start.checked_add(size_of::<Signature>()) else {
return false;
};
let signature = match packet.data(sig_start..sig_end) {
Some(signature) => Signature::new(signature),
None => return false,
let Some(signature) = packet.data(sig_start..sig_end).map(Signature::new) else {
return false;
};
let pubkey = match packet.data(pubkey_start..pubkey_end) {
Some(pubkey) => pubkey,
None => return false,
let Some(pubkey) = packet.data(pubkey_start..pubkey_end) else {
return false;
};
let message = match packet.data(msg_start..) {
Some(message) => message,
None => return false,
let Some(message) = packet.data(msg_start..) else {
return false;
};
if !signature.verify(pubkey, message) {
return false;
@ -317,9 +313,8 @@ fn do_get_packet_offsets(
pub fn check_for_tracer_packet(packet: &mut Packet) -> bool {
let first_pubkey_start: usize = TRACER_KEY_OFFSET_IN_TRANSACTION;
let first_pubkey_end = match first_pubkey_start.checked_add(size_of::<Pubkey>()) {
Some(offset) => offset,
None => return false,
let Some(first_pubkey_end) = first_pubkey_start.checked_add(size_of::<Pubkey>()) else {
return false;
};
// Check for tracer pubkey
match packet.data(first_pubkey_start..first_pubkey_end) {
@ -610,9 +605,8 @@ pub fn ed25519_verify(
reject_non_vote: bool,
valid_packet_count: usize,
) {
let api = match perf_libs::api() {
None => return ed25519_verify_cpu(batches, reject_non_vote, valid_packet_count),
Some(api) => api,
let Some(api) = perf_libs::api() else {
return ed25519_verify_cpu(batches, reject_non_vote, valid_packet_count);
};
let total_packet_count = count_packets_in_batches(batches);
// micro-benchmarks show GPU time for smallest batch around 15-20ms

View File

@ -23,12 +23,9 @@ impl Default for LogCollector {
impl LogCollector {
pub fn log(&mut self, message: &str) {
let limit = match self.bytes_limit {
Some(limit) => limit,
None => {
self.messages.push(message.to_string());
return;
}
let Some(limit) = self.bytes_limit else {
self.messages.push(message.to_string());
return;
};
let bytes_written = self.bytes_written.saturating_add(message.len());

View File

@ -549,11 +549,8 @@ declare_syscall!(
} else {
align_of::<u8>()
};
let layout = match Layout::from_size_align(size as usize, align) {
Ok(layout) => layout,
Err(_) => {
return Ok(0);
}
let Ok(layout) = Layout::from_size_align(size as usize, align) else {
return Ok(0);
};
let allocator = &mut invoke_context.get_syscall_context_mut()?.allocator;
if free_addr == 0 {
@ -631,11 +628,8 @@ declare_syscall!(
invoke_context.get_check_size(),
)?;
let new_address = match Pubkey::create_program_address(&seeds, program_id) {
Ok(address) => address,
Err(_) => {
return Ok(1);
}
let Ok(new_address) = Pubkey::create_program_address(&seeds, program_id) else {
return Ok(1);
};
let address = translate_slice_mut::<u8>(
memory_mapping,
@ -879,23 +873,14 @@ declare_syscall!(
invoke_context.get_check_size(),
)?;
let message = match libsecp256k1::Message::parse_slice(hash) {
Ok(msg) => msg,
Err(_) => {
return Ok(Secp256k1RecoverError::InvalidHash.into());
}
let Ok(message) = libsecp256k1::Message::parse_slice(hash) else {
return Ok(Secp256k1RecoverError::InvalidHash.into());
};
let adjusted_recover_id_val = match recovery_id_val.try_into() {
Ok(adjusted_recover_id_val) => adjusted_recover_id_val,
Err(_) => {
return Ok(Secp256k1RecoverError::InvalidRecoveryId.into());
}
let Ok(adjusted_recover_id_val) = recovery_id_val.try_into() else {
return Ok(Secp256k1RecoverError::InvalidRecoveryId.into());
};
let recovery_id = match libsecp256k1::RecoveryId::parse(adjusted_recover_id_val) {
Ok(id) => id,
Err(_) => {
return Ok(Secp256k1RecoverError::InvalidRecoveryId.into());
}
let Ok(recovery_id) = libsecp256k1::RecoveryId::parse(adjusted_recover_id_val) else {
return Ok(Secp256k1RecoverError::InvalidRecoveryId.into());
};
let sig_parse_result = if invoke_context
.feature_set
@ -906,11 +891,8 @@ declare_syscall!(
libsecp256k1::Signature::parse_overflowing_slice(signature)
};
let signature = match sig_parse_result {
Ok(sig) => sig,
Err(_) => {
return Ok(Secp256k1RecoverError::InvalidSignature.into());
}
let Ok(signature) = sig_parse_result else {
return Ok(Secp256k1RecoverError::InvalidSignature.into());
};
let public_key = match libsecp256k1::recover(&message, &signature, &recovery_id) {

View File

@ -206,13 +206,13 @@ mod tests {
let instructions =
config_instruction::create_account::<MyConfig>(&from_pubkey, &config_pubkey, 1, keys);
let system_instruction = limited_deserialize(&instructions[0].data).unwrap();
let space = match system_instruction {
SystemInstruction::CreateAccount {
lamports: _,
space,
owner: _,
} => space,
_ => panic!("Not a CreateAccount system instruction"),
let SystemInstruction::CreateAccount {
lamports: _,
space,
owner: _,
} = system_instruction
else {
panic!("Not a CreateAccount system instruction")
};
let config_account = AccountSharedData::new(0, space as usize, &id());
let accounts = process_instruction(

View File

@ -2464,11 +2464,11 @@ fn test_program_sbf_upgrade_via_cpi() {
.advance_slot(1, &Pubkey::default())
.expect("Failed to advance the slot");
let program_account = bank_client.get_account(&program_id).unwrap().unwrap();
let programdata_address = match program_account.state() {
Ok(bpf_loader_upgradeable::UpgradeableLoaderState::Program {
programdata_address,
}) => programdata_address,
_ => unreachable!(),
let Ok(bpf_loader_upgradeable::UpgradeableLoaderState::Program {
programdata_address,
}) = program_account.state()
else {
unreachable!()
};
let original_programdata = bank_client
.get_account_data(&programdata_address)

View File

@ -552,15 +552,13 @@ impl JsonRpcRequestProcessor {
slot: first_slot_in_epoch,
})?;
let first_confirmed_block = if let Ok(Some(first_confirmed_block)) = self
let Ok(Some(first_confirmed_block)) = self
.get_block(
first_confirmed_block_in_epoch,
Some(RpcBlockConfig::rewards_with_commitment(config.commitment).into()),
)
.await
{
first_confirmed_block
} else {
else {
return Err(RpcCustomError::BlockNotAvailable {
slot: first_confirmed_block_in_epoch,
}

View File

@ -407,13 +407,10 @@ async fn handle_connection(
}
}
}
let data_str = match str::from_utf8(&data) {
Ok(str) => str,
Err(_) => {
// Old implementation just closes the connection, so we preserve that behavior
// for now. It would be more correct to respond with an error.
break;
}
let Ok(data_str) = str::from_utf8(&data) else {
// Old implementation just closes the connection, so we preserve that behavior
// for now. It would be more correct to respond with an error.
break;
};
if let Some(response) = json_rpc_handler.handle_request(data_str).await {

View File

@ -4474,16 +4474,13 @@ impl AccountsDb {
let len = sorted_slots.len();
for slot in sorted_slots {
let old_storage = match self.get_storage_to_move_to_ancient_append_vec(
let Some(old_storage) = self.get_storage_to_move_to_ancient_append_vec(
slot,
&mut current_ancient,
can_randomly_shrink,
) {
Some(old_storages) => old_storages,
None => {
// nothing to squash for this slot
continue;
}
) else {
// nothing to squash for this slot
continue;
};
if guard.is_none() {

View File

@ -2667,15 +2667,12 @@ impl Bank {
if invalid_vote_keys.contains_key(vote_pubkey) {
return;
}
let stake_account = match self.get_account_with_fixed_root(stake_pubkey) {
Some(stake_account) => stake_account,
None => {
let Some(stake_account) = self.get_account_with_fixed_root(stake_pubkey) else {
invalid_stake_keys
.insert(*stake_pubkey, InvalidCacheEntryReason::Missing);
invalid_cached_stake_accounts.fetch_add(1, Relaxed);
return;
}
};
};
if cached_stake_account.account() != &stake_account {
if self.rc.accounts.accounts_db.assert_stakes_cache_consistency {
panic!(
@ -2886,23 +2883,17 @@ impl Bank {
};
let invalid_vote_keys = DashMap::<Pubkey, InvalidCacheEntryReason>::new();
let make_vote_delegations_entry = |vote_pubkey| {
let vote_account = match get_vote_account(&vote_pubkey) {
Some(vote_account) => vote_account,
None => {
invalid_vote_keys.insert(vote_pubkey, InvalidCacheEntryReason::Missing);
return None;
}
let Some(vote_account) = get_vote_account(&vote_pubkey) else {
invalid_vote_keys.insert(vote_pubkey, InvalidCacheEntryReason::Missing);
return None;
};
if vote_account.owner() != &solana_vote_program {
invalid_vote_keys.insert(vote_pubkey, InvalidCacheEntryReason::WrongOwner);
return None;
}
let vote_state = match vote_account.vote_state().cloned() {
Ok(vote_state) => vote_state,
Err(_) => {
invalid_vote_keys.insert(vote_pubkey, InvalidCacheEntryReason::BadState);
return None;
}
let Ok(vote_state) = vote_account.vote_state().cloned() else {
invalid_vote_keys.insert(vote_pubkey, InvalidCacheEntryReason::BadState);
return None;
};
let vote_with_stake_delegations = VoteWithStakeDelegations {
vote_state: Arc::new(vote_state),
@ -2921,11 +2912,11 @@ impl Bank {
// Join stake accounts with vote-accounts.
let push_stake_delegation = |(stake_pubkey, stake_account): (&Pubkey, &StakeAccount<_>)| {
let delegation = stake_account.delegation();
let mut vote_delegations =
match vote_with_stake_delegations_map.get_mut(&delegation.voter_pubkey) {
Some(vote_delegations) => vote_delegations,
None => return,
};
let Some(mut vote_delegations) =
vote_with_stake_delegations_map.get_mut(&delegation.voter_pubkey)
else {
return;
};
if let Some(reward_calc_tracer) = reward_calc_tracer.as_ref() {
let delegation =
InflationPointCalculationEvent::Delegation(delegation, solana_vote_program);
@ -3233,20 +3224,14 @@ impl Bank {
let delegation = stake_account.delegation();
let vote_pubkey = delegation.voter_pubkey;
let vote_account = match get_vote_account(&vote_pubkey) {
Some(vote_account) => vote_account,
None => {
return 0;
}
let Some(vote_account) = get_vote_account(&vote_pubkey) else {
return 0;
};
if vote_account.owner() != &solana_vote_program {
return 0;
}
let vote_state = match vote_account.vote_state() {
Ok(vote_state) => vote_state,
Err(_) => {
return 0;
}
let Ok(vote_state) = vote_account.vote_state() else {
return 0;
};
stake_state::calculate_points(
@ -3355,20 +3340,14 @@ impl Bank {
let (mut stake_account, stake_state) =
<(AccountSharedData, StakeState)>::from(stake_account);
let vote_pubkey = delegation.voter_pubkey;
let vote_account = match get_vote_account(&vote_pubkey) {
Some(vote_account) => vote_account,
None => {
return None;
}
let Some(vote_account) = get_vote_account(&vote_pubkey) else {
return None;
};
if vote_account.owner() != &solana_vote_program {
return None;
}
let vote_state = match vote_account.vote_state().cloned() {
Ok(vote_state) => vote_state,
Err(_) => {
return None;
}
let Ok(vote_state) = vote_account.vote_state().cloned() else {
return None;
};
let pre_lamport = stake_account.lamports();
@ -4866,9 +4845,7 @@ impl Bank {
}
pub fn load_program(&self, pubkey: &Pubkey) -> Arc<LoadedProgram> {
let program = if let Some(program) = self.get_account_with_fixed_root(pubkey) {
program
} else {
let Some(program) = self.get_account_with_fixed_root(pubkey) else {
return Arc::new(LoadedProgram::new_tombstone(
self.slot,
LoadedProgramType::Closed,

View File

@ -251,9 +251,8 @@ fn sanitize_path(entry_path: &Path, dst: &Path) -> Result<Option<PathBuf>> {
}
// Skip entries without a parent (i.e. outside of FS root)
let parent = match file_dst.parent() {
Some(p) => p,
None => return SKIP,
let Some(parent) = file_dst.parent() else {
return SKIP;
};
fs::create_dir_all(parent)?;

View File

@ -72,12 +72,9 @@ impl ReadOnlyAccountsCache {
pub(crate) fn load(&self, pubkey: Pubkey, slot: Slot) -> Option<AccountSharedData> {
let key = (pubkey, slot);
let mut entry = match self.cache.get_mut(&key) {
None => {
self.misses.fetch_add(1, Ordering::Relaxed);
return None;
}
Some(entry) => entry,
let Some(mut entry) = self.cache.get_mut(&key) else {
self.misses.fetch_add(1, Ordering::Relaxed);
return None;
};
self.hits.fetch_add(1, Ordering::Relaxed);
// Move the entry to the end of the queue.
@ -122,9 +119,8 @@ impl ReadOnlyAccountsCache {
// Evict entries from the front of the queue.
let mut num_evicts = 0;
while self.data_size.load(Ordering::Relaxed) > self.max_data_size {
let (pubkey, slot) = match self.queue.lock().unwrap().get_first() {
None => break,
Some(key) => *key,
let Some(&(pubkey, slot)) = self.queue.lock().unwrap().get_first() else {
break;
};
num_evicts += 1;
self.remove(pubkey, slot);

View File

@ -216,9 +216,8 @@ impl Stakes<StakeAccount> {
F: Fn(&Pubkey) -> Option<AccountSharedData>,
{
let stake_delegations = stakes.stake_delegations.iter().map(|(pubkey, delegation)| {
let stake_account = match get_account(pubkey) {
None => return Err(Error::StakeAccountNotFound(*pubkey)),
Some(account) => account,
let Some(stake_account) = get_account(pubkey) else {
return Err(Error::StakeAccountNotFound(*pubkey));
};
let stake_account = StakeAccount::try_from(stake_account)?;
// Sanity check that the delegation is consistent with what is
@ -231,9 +230,8 @@ impl Stakes<StakeAccount> {
});
// Assert that cached vote accounts are consistent with accounts-db.
for (pubkey, vote_account) in stakes.vote_accounts.iter() {
let account = match get_account(pubkey) {
None => return Err(Error::VoteAccountNotFound(*pubkey)),
Some(account) => account,
let Some(account) = get_account(pubkey) else {
return Err(Error::VoteAccountNotFound(*pubkey));
};
let vote_account = vote_account.account();
if vote_account != &account {
@ -250,9 +248,8 @@ impl Stakes<StakeAccount> {
.filter(|voter_pubkey| stakes.vote_accounts.get(voter_pubkey).is_none())
.collect();
for pubkey in voter_pubkeys {
let account = match get_account(&pubkey) {
None => continue,
Some(account) => account,
let Some(account) = get_account(&pubkey) else {
continue;
};
if VoteStateVersions::is_correct_size_and_initialized(account.data())
&& VoteAccount::try_from(account.clone()).is_ok()

View File

@ -179,9 +179,8 @@ impl VoteAccounts {
if stake == 0u64 {
return;
}
let staked_nodes = match self.staked_nodes.get_mut() {
None => return,
Some(staked_nodes) => staked_nodes,
let Some(staked_nodes) = self.staked_nodes.get_mut() else {
return;
};
if let Some(node_pubkey) = vote_account.node_pubkey() {
Arc::make_mut(staked_nodes)
@ -195,9 +194,8 @@ impl VoteAccounts {
if stake == 0u64 {
return;
}
let staked_nodes = match self.staked_nodes.get_mut() {
None => return,
Some(staked_nodes) => staked_nodes,
let Some(staked_nodes) = self.staked_nodes.get_mut() else {
return;
};
if let Some(node_pubkey) = vote_account.node_pubkey() {
match Arc::make_mut(staked_nodes).entry(node_pubkey) {

View File

@ -339,9 +339,8 @@ fn postprocess_dump(program_dump: &Path) {
let mut rel: HashMap<u64, String> = HashMap::new();
let mut name = String::from("");
let mut state = 0;
let file = match File::open(program_dump) {
Ok(x) => x,
_ => return,
let Ok(file) = File::open(program_dump) else {
return;
};
for line_result in BufReader::new(file).lines() {
let line = line_result.unwrap();
@ -371,14 +370,12 @@ fn postprocess_dump(program_dump: &Path) {
}
}
}
let file = match File::create(&postprocessed_dump) {
Ok(x) => x,
_ => return,
let Ok(file) = File::create(&postprocessed_dump) else {
return;
};
let mut out = BufWriter::new(file);
let file = match File::open(program_dump) {
Ok(x) => x,
_ => return,
let Ok(file) = File::open(program_dump) else {
return;
};
let mut pc = 0u64;
let mut step = 0u64;
@ -426,9 +423,8 @@ fn postprocess_dump(program_dump: &Path) {
// not known to the runtime and warn about them if any.
fn check_undefined_symbols(config: &Config, program: &Path) {
let syscalls_txt = config.sbf_sdk.join("syscalls.txt");
let file = match File::open(syscalls_txt) {
Ok(x) => x,
_ => return,
let Ok(file) = File::open(syscalls_txt) else {
return;
};
let mut syscalls = HashSet::new();
for line_result in BufReader::new(file).lines() {

View File

@ -44,17 +44,14 @@ fn main() {
*/
fn transform(inc: &PathBuf) {
let inc_path = PathBuf::from(inc);
let filename = match inc_path.file_name() {
Some(f) => f,
None => return,
let Some(filename) = inc_path.file_name() else {
return;
};
let parent = match inc_path.parent() {
Some(f) => f,
None => return,
let Some(parent) = inc_path.parent() else {
return;
};
let parent = match parent.parent() {
Some(f) => f,
None => return,
let Some(parent) = parent.parent() else {
return;
};
let mut header_path = PathBuf::from(parent);
let mut filename = PathBuf::from(filename);

View File

@ -73,10 +73,9 @@ macro_rules! impl_var_int {
let mut out = 0;
let mut shift = 0u32;
while shift < <$type>::BITS {
let byte = match seq.next_element::<u8>()? {
None => return Err(A::Error::custom("Invalid Sequence")),
Some(byte) => byte,
};
let Some(byte) = seq.next_element::<u8>()? else {
return Err(A::Error::custom("Invalid Sequence"));
};
out |= ((byte & 0x7F) as Self) << shift;
if byte & 0x80 == 0 {
// Last byte should not have been truncated when it was

View File

@ -686,15 +686,11 @@ pub mod serde_compact_vote_state_update {
let lockout_offsets = vote_state_update.lockouts.iter().scan(
vote_state_update.root.unwrap_or_default(),
|slot, lockout| {
let offset = match lockout.slot().checked_sub(*slot) {
None => return Some(Err(serde::ser::Error::custom("Invalid vote lockout"))),
Some(offset) => offset,
let Some(offset) = lockout.slot().checked_sub(*slot) else {
return Some(Err(serde::ser::Error::custom("Invalid vote lockout")));
};
let confirmation_count = match u8::try_from(lockout.confirmation_count()) {
Ok(confirmation_count) => confirmation_count,
Err(_) => {
return Some(Err(serde::ser::Error::custom("Invalid confirmation count")))
}
let Ok(confirmation_count) = u8::try_from(lockout.confirmation_count()) else {
return Some(Err(serde::ser::Error::custom("Invalid confirmation count")));
};
let lockout_offset = LockoutOffset {
offset,

View File

@ -560,12 +560,11 @@ impl AccountSharedData {
}
pub fn set_data_from_slice(&mut self, new_data: &[u8]) {
let data = match Arc::get_mut(&mut self.data) {
// The buffer isn't shared, so we're going to memcpy in place.
Some(data) => data,
// If the buffer isn't shared, we're going to memcpy in place.
let Some(data) = Arc::get_mut(&mut self.data) else {
// If the buffer is shared, the cheapest thing to do is to clone the
// incoming slice and replace the buffer.
None => return self.set_data(new_data.to_vec()),
return self.set_data(new_data.to_vec());
};
let new_len = new_data.len();

View File

@ -796,9 +796,8 @@ async fn handle_chunk(
stats.total_invalid_chunks.fetch_add(1, Ordering::Relaxed);
return true;
}
let end_of_chunk = match chunk.offset.checked_add(chunk_len) {
Some(end) => end,
None => return true,
let Some(end_of_chunk) = chunk.offset.checked_add(chunk_len) else {
return true;
};
if end_of_chunk > PACKET_DATA_SIZE as u64 {
stats
@ -819,10 +818,9 @@ async fn handle_chunk(
if let Some(accum) = packet_accum.as_mut() {
let offset = chunk.offset;
let end_of_chunk = match (chunk.offset as usize).checked_add(chunk.bytes.len())
{
Some(end) => end,
None => return true,
let Some(end_of_chunk) = (chunk.offset as usize).checked_add(chunk.bytes.len())
else {
return true;
};
accum.chunks.push(PacketChunk {
bytes: chunk.bytes,

View File

@ -367,9 +367,8 @@ impl TestValidatorGenesis {
accounts: &[AccountInfo],
) -> Result<&mut Self, String> {
for account in accounts {
let account_path = match solana_program_test::find_file(account.filename) {
Some(path) => path,
None => return Err(format!("Unable to locate {}", account.filename)),
let Some(account_path) = solana_program_test::find_file(account.filename) else {
return Err(format!("Unable to locate {}", account.filename));
};
let mut file = File::open(&account_path).unwrap();
let mut account_info_raw = String::new();

View File

@ -42,9 +42,8 @@ pub(super) fn recv_slot_entries(receiver: &Receiver<WorkingBankEntry>) -> Result
// Drain channel
while last_tick_height != bank.max_tick_height() {
let (try_bank, (entry, tick_height)) = match receiver.try_recv() {
Ok(working_bank_entry) => working_bank_entry,
Err(_) => break,
let Ok((try_bank, (entry, tick_height))) = receiver.try_recv() else {
break;
};
// If the bank changed, that implies the previous slot was interrupted and we do not have to
// broadcast its entries.
@ -65,11 +64,11 @@ pub(super) fn recv_slot_entries(receiver: &Receiver<WorkingBankEntry>) -> Result
while last_tick_height != bank.max_tick_height()
&& serialized_batch_byte_count < target_serialized_batch_byte_count
{
let (try_bank, (entry, tick_height)) =
match receiver.recv_deadline(coalesce_start + ENTRY_COALESCE_DURATION) {
Ok(working_bank_entry) => working_bank_entry,
Err(_) => break,
};
let Ok((try_bank, (entry, tick_height))) =
receiver.recv_deadline(coalesce_start + ENTRY_COALESCE_DURATION)
else {
break;
};
// If the bank changed, that implies the previous slot was interrupted and we do not have to
// broadcast its entries.
if try_bank.slot() != bank.slot() {

View File

@ -224,13 +224,10 @@ fn retransmit(
// and if the leader is unknown they should fail signature check.
// So here we should expect to know the slot leader and otherwise
// skip the shred.
let slot_leader = match leader_schedule_cache.slot_leader_at(slot, Some(&working_bank))
{
Some(pubkey) => pubkey,
None => {
stats.unknown_shred_slot_leader += shreds.len();
return None;
}
let Some(slot_leader) = leader_schedule_cache.slot_leader_at(slot, Some(&working_bank))
else {
stats.unknown_shred_slot_leader += shreds.len();
return None;
};
let cluster_nodes =
cluster_nodes_cache.get(slot, &root_bank, &working_bank, cluster_info);

View File

@ -71,14 +71,13 @@ impl Dashboard {
let progress_bar = new_spinner_progress_bar();
progress_bar.set_message("Connecting...");
let (rpc_addr, start_time) = match runtime.block_on(wait_for_validator_startup(
let Some((rpc_addr, start_time)) = runtime.block_on(wait_for_validator_startup(
&ledger_path,
&exit,
progress_bar,
refresh_interval,
)) {
None => continue,
Some(results) => results,
)) else {
continue;
};
let rpc_client = RpcClient::new_socket(rpc_addr);

View File

@ -125,9 +125,8 @@ fn wait_for_restart_window(
.block_on(async move { admin_client.await?.rpc_addr().await })
.map_err(|err| format!("Unable to get validator RPC address: {err}"))?;
let rpc_client = match rpc_addr {
None => return Err("RPC not available".into()),
Some(rpc_addr) => RpcClient::new_socket(rpc_addr),
let Some(rpc_client) = rpc_addr.map(RpcClient::new_socket) else {
return Err("RPC not available".into());
};
let my_identity = rpc_client.get_identity()?;