From 9598961adf05a96ac80daddf8e3b9afb2e147185 Mon Sep 17 00:00:00 2001 From: gelash Date: Thu, 26 Sep 2024 17:13:45 +0400 Subject: [PATCH] ok_or and map_or audit --- api/src/context.rs | 4 +-- .../verifier/transaction_arg_validation.rs | 14 +++++++---- aptos-move/block-executor/src/executor.rs | 8 +++--- .../src/txn_last_input_output.rs | 22 ++++++++-------- .../natives/aggregator_natives/helpers_v1.rs | 20 +++++++-------- config/src/config/node_config_loader.rs | 6 ++--- config/src/config/secure_backend_config.rs | 2 +- consensus/consensus-types/src/sync_info.rs | 2 +- consensus/src/dag/adapter.rs | 12 +++++---- consensus/src/liveness/leader_reputation.rs | 12 +++++---- consensus/src/liveness/round_state.rs | 2 +- consensus/src/persistent_liveness_storage.rs | 4 +-- .../aptos-dkg/src/weighted_vuf/pinkas/mod.rs | 4 +-- crates/aptos/src/account/multisig_account.rs | 6 ++--- crates/aptos/src/common/init.rs | 6 ++--- crates/aptos/src/common/types.rs | 4 +-- .../aptos/src/governance/delegation_pool.rs | 21 ++++++++-------- crates/aptos/src/move_tool/mod.rs | 2 +- .../src/input_processing/witness_gen.rs | 4 ++- mempool/src/shared_mempool/network.rs | 4 +-- secure/storage/src/on_disk.rs | 2 +- .../data-streaming-service/src/data_stream.rs | 9 ++++--- storage/aptosdb/src/db/fake_aptosdb.rs | 2 +- .../src/db/include/aptosdb_internal.rs | 15 ++++++----- storage/aptosdb/src/ledger_db/event_db.rs | 6 ++--- .../src/ledger_db/ledger_metadata_db.rs | 25 ++++++++----------- storage/aptosdb/src/ledger_db/write_set_db.rs | 5 +--- .../backup/backup-cli/src/metadata/view.rs | 8 +++--- .../move/move-prover/lab/src/benchmark.rs | 2 +- third_party/move/move-prover/lab/src/plot.rs | 2 +- .../src/compilation/compiled_package.rs | 2 +- types/src/block_info.rs | 4 +-- 32 files changed, 123 insertions(+), 118 deletions(-) diff --git a/api/src/context.rs b/api/src/context.rs index 2de3374a5c00a..1a77f5d5ee1f4 100644 --- a/api/src/context.rs +++ b/api/src/context.rs @@ -858,7 +858,7 @@ impl Context { } else { self.indexer_reader .as_ref() - .ok_or(anyhow!("Indexer reader is None")) + .ok_or_else(|| anyhow!("Indexer reader is None")) .map_err(|err| { E::internal_with_code(err, AptosErrorCode::InternalError, ledger_info) })? @@ -957,7 +957,7 @@ impl Context { } else { self.indexer_reader .as_ref() - .ok_or(anyhow!("Internal indexer reader doesn't exist"))? + .ok_or_else(|| anyhow!("Internal indexer reader doesn't exist"))? .get_events(event_key, start, order, limit as u64, ledger_version)? }; if order == Order::Descending { diff --git a/aptos-move/aptos-vm/src/verifier/transaction_arg_validation.rs b/aptos-move/aptos-vm/src/verifier/transaction_arg_validation.rs index b4be0a60880de..2ee495c5b10a6 100644 --- a/aptos-move/aptos-vm/src/verifier/transaction_arg_validation.rs +++ b/aptos-move/aptos-vm/src/verifier/transaction_arg_validation.rs @@ -455,11 +455,15 @@ fn validate_and_construct( )?; let mut ret_vals = serialized_result.return_values; // We know ret_vals.len() == 1 - let deserialize_error = VMStatus::error( - StatusCode::INTERNAL_TYPE_ERROR, - Some(String::from("Constructor did not return value")), - ); - Ok(ret_vals.pop().ok_or(deserialize_error)?.0) + Ok(ret_vals + .pop() + .ok_or_else(|| { + VMStatus::error( + StatusCode::INTERNAL_TYPE_ERROR, + Some(String::from("Constructor did not return value")), + ) + })? + .0) } // String is a vector of bytes, so both string and vector carry a length in the serialized format. diff --git a/aptos-move/block-executor/src/executor.rs b/aptos-move/block-executor/src/executor.rs index 90be88920d6a1..43616a636ab4c 100644 --- a/aptos-move/block-executor/src/executor.rs +++ b/aptos-move/block-executor/src/executor.rs @@ -120,12 +120,12 @@ where let execute_result = executor.execute_transaction(&sync_view, txn, idx_to_execute); let mut prev_modified_keys = last_input_output - .modified_keys::(idx_to_execute) - .map_or(HashMap::new(), |keys| keys.collect()); + .modified_keys(idx_to_execute, true) + .map_or_else(HashMap::new, |keys| keys.collect()); let mut prev_modified_delayed_fields = last_input_output .delayed_field_keys(idx_to_execute) - .map_or(HashSet::new(), |keys| keys.collect()); + .map_or_else(HashSet::new, |keys| keys.collect()); let mut read_set = sync_view.take_parallel_reads(); if read_set.is_incorrect_use() { @@ -398,7 +398,7 @@ where clear_speculative_txn_logs(txn_idx as usize); // Not valid and successfully aborted, mark the latest write/delta sets as estimates. - if let Some(keys) = last_input_output.modified_keys::(txn_idx) { + if let Some(keys) = last_input_output.modified_keys(txn_idx, false) { for (k, kind) in keys { use KeyKind::*; match kind { diff --git a/aptos-move/block-executor/src/txn_last_input_output.rs b/aptos-move/block-executor/src/txn_last_input_output.rs index 95ffa57680608..bc6b203f28b25 100644 --- a/aptos-move/block-executor/src/txn_last_input_output.rs +++ b/aptos-move/block-executor/src/txn_last_input_output.rs @@ -35,7 +35,7 @@ macro_rules! forward_on_success_or_skip_rest { $self.outputs[$txn_idx as usize] .load() .as_ref() - .map_or(vec![], |txn_output| match txn_output.as_ref() { + .map_or_else(Vec::new, |txn_output| match txn_output.as_ref() { ExecutionStatus::Success(t) | ExecutionStatus::SkipRest(t) => t.$f(), ExecutionStatus::Abort(_) | ExecutionStatus::SpeculativeExecutionAbortError(_) @@ -273,15 +273,15 @@ impl, E: Debug + Send + Clone> } // Extracts a set of paths (keys) written or updated during execution from transaction - // output, .1 for each item is false for non-module paths and true for module paths. - // If TAKE_GROUP_TAGS is set, the final HashSet of tags is moved for the group key - - // should be called once for each incarnation / record due to 'take'. if TAKE_GROUP_TAGS - // is false, stored modified group resource tags in the group are cloned out. - pub(crate) fn modified_keys( + // output, with corresponding KeyKind. If take_group_tags is true, the final HashSet + // of tags is moved for the group key - should be called once for each incarnation / record + // due to 'take'. if false, stored modified group resource tags in the group are cloned out. + pub(crate) fn modified_keys( &self, txn_idx: TxnIndex, + take_group_tags: bool, ) -> Option)>> { - let group_keys_and_tags: Vec<(T::Key, HashSet)> = if TAKE_GROUP_TAGS { + let group_keys_and_tags: Vec<(T::Key, HashSet)> = if take_group_tags { std::mem::take(&mut self.resource_group_keys_and_tags[txn_idx as usize].acquire()) } else { self.resource_group_keys_and_tags[txn_idx as usize] @@ -367,9 +367,9 @@ impl, E: Debug + Send + Clone> &self, txn_idx: TxnIndex, ) -> Box)>> { - self.outputs[txn_idx as usize].load().as_ref().map_or( - Box::new(empty::<(T::Event, Option)>()), - |txn_output| match txn_output.as_ref() { + match self.outputs[txn_idx as usize].load().as_ref() { + None => Box::new(empty::<(T::Event, Option)>()), + Some(txn_output) => match txn_output.as_ref() { ExecutionStatus::Success(t) | ExecutionStatus::SkipRest(t) => { let events = t.get_events(); Box::new(events.into_iter()) @@ -380,7 +380,7 @@ impl, E: Debug + Send + Clone> Box::new(empty::<(T::Event, Option)>()) }, }, - ) + } } pub(crate) fn take_resource_write_set( diff --git a/aptos-move/framework/src/natives/aggregator_natives/helpers_v1.rs b/aptos-move/framework/src/natives/aggregator_natives/helpers_v1.rs index 99d1211a5ea10..a633a3df3d9c8 100644 --- a/aptos-move/framework/src/natives/aggregator_natives/helpers_v1.rs +++ b/aptos-move/framework/src/natives/aggregator_natives/helpers_v1.rs @@ -56,19 +56,17 @@ pub(crate) fn unpack_aggregator_struct( let pop_with_err = |vec: &mut Vec, msg: &str| { vec.pop() - .map_or(Err(extension_error(msg)), |v| v.value_as::()) + .map_or_else(|| Err(extension_error(msg)), |v| v.value_as::()) }; let limit = pop_with_err(&mut fields, "unable to pop 'limit' field")?; - let key = fields - .pop() - .map_or(Err(extension_error("unable to pop `handle` field")), |v| { - v.value_as::() - })?; - let handle = fields - .pop() - .map_or(Err(extension_error("unable to pop `handle` field")), |v| { - v.value_as::() - })?; + let key = fields.pop().map_or_else( + || Err(extension_error("unable to pop `handle` field")), + |v| v.value_as::(), + )?; + let handle = fields.pop().map_or_else( + || Err(extension_error("unable to pop `handle` field")), + |v| v.value_as::(), + )?; Ok((TableHandle(handle), key, limit)) } diff --git a/config/src/config/node_config_loader.rs b/config/src/config/node_config_loader.rs index b5235620ddf58..62a694f9bfacd 100644 --- a/config/src/config/node_config_loader.rs +++ b/config/src/config/node_config_loader.rs @@ -159,9 +159,9 @@ fn get_chain_id(node_config: &NodeConfig) -> Result { // TODO: can we make this less hacky? // Load the genesis transaction from disk - let genesis_txn = get_genesis_txn(node_config).ok_or(Error::InvariantViolation( - "The genesis transaction was not found!".to_string(), - ))?; + let genesis_txn = get_genesis_txn(node_config).ok_or_else(|| { + Error::InvariantViolation("The genesis transaction was not found!".to_string()) + })?; // Extract the chain ID from the genesis transaction match genesis_txn { diff --git a/config/src/config/secure_backend_config.rs b/config/src/config/secure_backend_config.rs index 62bf3b0c041e6..b0db79659caa5 100644 --- a/config/src/config/secure_backend_config.rs +++ b/config/src/config/secure_backend_config.rs @@ -79,7 +79,7 @@ impl VaultConfig { let path = self .ca_certificate .as_ref() - .ok_or(Error::Missing("ca_certificate"))?; + .ok_or_else(|| Error::Missing("ca_certificate"))?; read_file(path) } } diff --git a/consensus/consensus-types/src/sync_info.rs b/consensus/consensus-types/src/sync_info.rs index 7507dc2be81c3..0c8171016e610 100644 --- a/consensus/consensus-types/src/sync_info.rs +++ b/consensus/consensus-types/src/sync_info.rs @@ -42,7 +42,7 @@ impl Display for SyncInfo { self.highest_timeout_round(), self.highest_commit_round(), self.highest_quorum_cert, - self.highest_ordered_cert.as_ref().map_or("None".to_string(), |cert| cert.to_string()), + self.highest_ordered_cert.as_ref().map_or_else(|| "None".to_string(), |cert| cert.to_string()), self.highest_commit_cert, ) } diff --git a/consensus/src/dag/adapter.rs b/consensus/src/dag/adapter.rs index 36bd615345b04..36941b875cbdb 100644 --- a/consensus/src/dag/adapter.rs +++ b/consensus/src/dag/adapter.rs @@ -297,11 +297,13 @@ impl StorageAdapter { usize::try_from(*index) .map_err(|_err| anyhow!("index {} out of bounds", index)) .and_then(|index| { - validators.get(index).cloned().ok_or(anyhow!( - "index {} is larger than number of validators {}", - index, - validators.len() - )) + validators.get(index).cloned().ok_or_else(|| { + anyhow!( + "index {} is larger than number of validators {}", + index, + validators.len() + ) + }) }) }) .collect() diff --git a/consensus/src/liveness/leader_reputation.rs b/consensus/src/liveness/leader_reputation.rs index dfeabed8181bd..ccd82776d98da 100644 --- a/consensus/src/liveness/leader_reputation.rs +++ b/consensus/src/liveness/leader_reputation.rs @@ -283,11 +283,13 @@ impl NewBlockEventAggregation { usize::try_from(*index) .map_err(|_err| format!("index {} out of bounds", index)) .and_then(|index| { - validators.get(index).ok_or(format!( - "index {} is larger than number of validators {}", - index, - validators.len() - )) + validators.get(index).ok_or_else(|| { + format!( + "index {} is larger than number of validators {}", + index, + validators.len() + ) + }) }) }) .collect() diff --git a/consensus/src/liveness/round_state.rs b/consensus/src/liveness/round_state.rs index 2c7ea4c198da6..bef7b31b44fe3 100644 --- a/consensus/src/liveness/round_state.rs +++ b/consensus/src/liveness/round_state.rs @@ -376,7 +376,7 @@ impl RoundState { round = self.current_round, "{:?} passed since the previous deadline.", now.checked_sub(self.current_round_deadline) - .map_or("0 ms".to_string(), |v| format!("{:?}", v)) + .map_or_else(|| "0 ms".to_string(), |v| format!("{:?}", v)) ); debug!( round = self.current_round, diff --git a/consensus/src/persistent_liveness_storage.rs b/consensus/src/persistent_liveness_storage.rs index 7e69b3304f653..0b09759e2fa06 100644 --- a/consensus/src/persistent_liveness_storage.rs +++ b/consensus/src/persistent_liveness_storage.rs @@ -436,8 +436,8 @@ impl PersistentLivenessStorage for StorageWriteProxy { } info!( "Starting up the consensus state machine with recovery data - [last_vote {}], [highest timeout certificate: {}]", - initial_data.last_vote.as_ref().map_or("None".to_string(), |v| v.to_string()), - initial_data.highest_2chain_timeout_certificate().as_ref().map_or("None".to_string(), |v| v.to_string()), + initial_data.last_vote.as_ref().map_or_else(|| "None".to_string(), |v| v.to_string()), + initial_data.highest_2chain_timeout_certificate().as_ref().map_or_else(|| "None".to_string(), |v| v.to_string()), ); LivenessStorageData::FullRecoveryData(initial_data) diff --git a/crates/aptos-dkg/src/weighted_vuf/pinkas/mod.rs b/crates/aptos-dkg/src/weighted_vuf/pinkas/mod.rs index dd3795830f9ea..254ff831a3d26 100644 --- a/crates/aptos-dkg/src/weighted_vuf/pinkas/mod.rs +++ b/crates/aptos-dkg/src/weighted_vuf/pinkas/mod.rs @@ -246,7 +246,7 @@ impl WeightedVUF for PinkasWUF { pis.push( apks[player.id] .as_ref() - .ok_or(anyhow!("Missing APK for player {}", player.get_id()))? + .ok_or_else(|| anyhow!("Missing APK for player {}", player.get_id()))? .0 .pi, ); @@ -299,7 +299,7 @@ impl PinkasWUF { let apk = apks[player.id] .as_ref() - .ok_or(anyhow!("Missing APK for player {}", player.get_id()))?; + .ok_or_else(|| anyhow!("Missing APK for player {}", player.get_id()))?; rks.push(&apk.0.rks); shares.push(share); diff --git a/crates/aptos/src/account/multisig_account.rs b/crates/aptos/src/account/multisig_account.rs index a65a351cec56f..637a613aa0a33 100644 --- a/crates/aptos/src/account/multisig_account.rs +++ b/crates/aptos/src/account/multisig_account.rs @@ -200,11 +200,11 @@ impl CliCommand for VerifyProposal { .to_hex_literal() // If full payload not provided, get payload hash directly from transaction proposal: } else { - view_json_option_str(&multisig_transaction["payload_hash"])?.ok_or( + view_json_option_str(&multisig_transaction["payload_hash"])?.ok_or_else(|| { CliError::UnexpectedError( "Neither payload nor payload hash provided on-chain".to_string(), - ), - )? + ) + })? }; // Get verification result based on if expected and actual payload hashes match. if expected_payload_hash.eq(&actual_payload_hash) { diff --git a/crates/aptos/src/common/init.rs b/crates/aptos/src/common/init.rs index 46a5a7da8f6ad..db590ff97faea 100644 --- a/crates/aptos/src/common/init.rs +++ b/crates/aptos/src/common/init.rs @@ -231,9 +231,9 @@ impl CliCommand<()> for InitTool { let public_key = if self.is_hardware_wallet() { let pub_key = match aptos_ledger::get_public_key( derivation_path - .ok_or(CliError::UnexpectedError( - "Invalid derivation path".to_string(), - ))? + .ok_or_else(|| { + CliError::UnexpectedError("Invalid derivation path".to_string()) + })? .as_str(), false, ) { diff --git a/crates/aptos/src/common/types.rs b/crates/aptos/src/common/types.rs index 779e1c26b163d..0b5fc13047670 100644 --- a/crates/aptos/src/common/types.rs +++ b/crates/aptos/src/common/types.rs @@ -2218,9 +2218,7 @@ impl TryInto for &EntryFunctionArguments { fn try_into(self) -> Result { self.function_id .clone() - .ok_or(CliError::CommandArgumentError( - "No function ID provided".to_string(), - )) + .ok_or_else(|| CliError::CommandArgumentError("No function ID provided".to_string())) } } diff --git a/crates/aptos/src/governance/delegation_pool.rs b/crates/aptos/src/governance/delegation_pool.rs index 5d836241af694..b6824e179e84f 100644 --- a/crates/aptos/src/governance/delegation_pool.rs +++ b/crates/aptos/src/governance/delegation_pool.rs @@ -222,13 +222,13 @@ async fn is_partial_governance_voting_enabled_for_delegation_pool( None, ) .await?; - response.inner()[0] - .as_bool() - .ok_or(CliError::UnexpectedError( + response.inner()[0].as_bool().ok_or_else(|| { + CliError::UnexpectedError( "Unexpected response from node when checking if partial governance_voting is \ enabled for delegation pool" .to_string(), - )) + ) + }) } async fn get_remaining_voting_power( @@ -255,14 +255,13 @@ async fn get_remaining_voting_power( None, ) .await?; - let remaining_voting_power_str = - response.inner()[0] - .as_str() - .ok_or(CliError::UnexpectedError(format!( - "Unexpected response from node when getting remaining voting power of {}\ + let remaining_voting_power_str = response.inner()[0].as_str().ok_or_else(|| { + CliError::UnexpectedError(format!( + "Unexpected response from node when getting remaining voting power of {}\ in delegation pool {}", - pool_address, voter_address - )))?; + pool_address, voter_address + )) + })?; remaining_voting_power_str.parse().map_err(|err| { CliError::UnexpectedError(format!( "Unexpected response from node when getting remaining voting power of {}\ diff --git a/crates/aptos/src/move_tool/mod.rs b/crates/aptos/src/move_tool/mod.rs index 72b8c243b891d..4b15f51e6b63e 100644 --- a/crates/aptos/src/move_tool/mod.rs +++ b/crates/aptos/src/move_tool/mod.rs @@ -1569,7 +1569,7 @@ async fn submit_chunked_publish_transactions( match result { Ok(tx_summary) => { let tx_hash = tx_summary.transaction_hash.to_string(); - let status = tx_summary.success.map_or("".to_string(), |success| { + let status = tx_summary.success.map_or_else(String::new, |success| { if success { "Success".to_string() } else { diff --git a/keyless/common/src/input_processing/witness_gen.rs b/keyless/common/src/input_processing/witness_gen.rs index baaf2e783e6ff..6df60c3822113 100644 --- a/keyless/common/src/input_processing/witness_gen.rs +++ b/keyless/common/src/input_processing/witness_gen.rs @@ -12,7 +12,9 @@ pub trait PathStr { impl PathStr for NamedTempFile { fn path_str(&self) -> Result<&str> { - self.path().to_str().ok_or(anyhow!("tempfile path error")) + self.path() + .to_str() + .ok_or_else(|| anyhow!("tempfile path error")) } } diff --git a/mempool/src/shared_mempool/network.rs b/mempool/src/shared_mempool/network.rs index 36a672721093d..3f5bee5f9b520 100644 --- a/mempool/src/shared_mempool/network.rs +++ b/mempool/src/shared_mempool/network.rs @@ -370,7 +370,7 @@ impl> MempoolNetworkInterf // If we don't have any info about the node, we shouldn't broadcast to it let state = sync_states .get_mut(&peer) - .ok_or(BroadcastError::PeerNotFound(peer))?; + .ok_or_else(|| BroadcastError::PeerNotFound(peer))?; // If backoff mode is on for this peer, only execute broadcasts that were scheduled as a backoff broadcast. // This is to ensure the backoff mode is actually honored (there is a chance a broadcast was scheduled @@ -607,7 +607,7 @@ impl> MempoolNetworkInterf let mut sync_states = self.sync_states.write(); let state = sync_states .get_mut(&peer) - .ok_or(BroadcastError::PeerNotFound(peer))?; + .ok_or_else(|| BroadcastError::PeerNotFound(peer))?; // Update peer sync state with info from above broadcast. state.update(&message_id); diff --git a/secure/storage/src/on_disk.rs b/secure/storage/src/on_disk.rs index a896d8b4ef39c..dfbb921a6f07f 100644 --- a/secure/storage/src/on_disk.rs +++ b/secure/storage/src/on_disk.rs @@ -42,7 +42,7 @@ impl OnDiskStorage { // working directory provided by PathBuf::new(). let file_dir = file_path .parent() - .map_or(PathBuf::new(), |p| p.to_path_buf()); + .map_or_else(PathBuf::new, |p| p.to_path_buf()); Self { file_path, diff --git a/state-sync/data-streaming-service/src/data_stream.rs b/state-sync/data-streaming-service/src/data_stream.rs index 95bf16a173d80..68e8fbe4abaa7 100644 --- a/state-sync/data-streaming-service/src/data_stream.rs +++ b/state-sync/data-streaming-service/src/data_stream.rs @@ -588,9 +588,12 @@ impl DataStream { .advertised_data .highest_synced_ledger_info() .map(|ledger_info| ledger_info.ledger_info().version()) - .ok_or(aptos_data_client::error::Error::UnexpectedErrorEncountered( - "The highest synced ledger info is missing from the global data summary!".into(), - ))?; + .ok_or_else(|| { + aptos_data_client::error::Error::UnexpectedErrorEncountered( + "The highest synced ledger info is missing from the global data summary!" + .into(), + ) + })?; // If the stream is not lagging behind, reset the lag and return if highest_response_version >= highest_advertised_version { diff --git a/storage/aptosdb/src/db/fake_aptosdb.rs b/storage/aptosdb/src/db/fake_aptosdb.rs index c15a1ea742dea..325c9fe4228c9 100644 --- a/storage/aptosdb/src/db/fake_aptosdb.rs +++ b/storage/aptosdb/src/db/fake_aptosdb.rs @@ -1117,7 +1117,7 @@ mod tests { let signed_transaction = transaction_with_proof .transaction .try_as_signed_user_txn() - .ok_or(anyhow!("not user transaction"))?; + .ok_or_else(|| anyhow!("not user transaction"))?; ensure!( transaction_with_proof.version == version, diff --git a/storage/aptosdb/src/db/include/aptosdb_internal.rs b/storage/aptosdb/src/db/include/aptosdb_internal.rs index 73cc62d2dafd0..d31b38778e1df 100644 --- a/storage/aptosdb/src/db/include/aptosdb_internal.rs +++ b/storage/aptosdb/src/db/include/aptosdb_internal.rs @@ -1,9 +1,9 @@ // Copyright © Aptos Foundation // SPDX-License-Identifier: Apache-2.0 +use crate::metrics::CONCURRENCY_GAUGE; use aptos_metrics_core::IntGaugeHelper; use aptos_storage_interface::block_info::BlockInfo; -use crate::metrics::CONCURRENCY_GAUGE; impl AptosDB { fn new_with_dbs( @@ -44,8 +44,11 @@ impl AptosDB { internal_indexer_db.clone(), )); - let ledger_pruner = - LedgerPrunerManager::new(Arc::clone(&ledger_db), pruner_config.ledger_pruner_config, internal_indexer_db); + let ledger_pruner = LedgerPrunerManager::new( + Arc::clone(&ledger_db), + pruner_config.ledger_pruner_config, + internal_indexer_db, + ); AptosDB { ledger_db: Arc::clone(&ledger_db), @@ -247,9 +250,9 @@ impl AptosDB { .ledger_db .metadata_db() .get_block_info(block_height)? - .ok_or(AptosDbError::NotFound(format!( - "BlockInfo not found at height {block_height}" - )))?) + .ok_or_else(|| { + AptosDbError::NotFound(format!("BlockInfo not found at height {block_height}")) + })?) } } diff --git a/storage/aptosdb/src/ledger_db/event_db.rs b/storage/aptosdb/src/ledger_db/event_db.rs index 235df9b29a1ca..f34586cfbb42d 100644 --- a/storage/aptosdb/src/ledger_db/event_db.rs +++ b/storage/aptosdb/src/ledger_db/event_db.rs @@ -105,9 +105,9 @@ impl EventDb { Ok(EventsByVersionIter::new( iter, start_version, - start_version.checked_add(num_versions as u64).ok_or({ - AptosDbError::TooManyRequested(num_versions as u64, Version::max_value()) - })?, + start_version.checked_add(num_versions as u64).ok_or( + AptosDbError::TooManyRequested(num_versions as u64, Version::max_value()), + )?, )) } diff --git a/storage/aptosdb/src/ledger_db/ledger_metadata_db.rs b/storage/aptosdb/src/ledger_db/ledger_metadata_db.rs index d8661d7a4c46a..40ace0969239d 100644 --- a/storage/aptosdb/src/ledger_db/ledger_metadata_db.rs +++ b/storage/aptosdb/src/ledger_db/ledger_metadata_db.rs @@ -107,15 +107,13 @@ impl LedgerMetadataDb { } pub(crate) fn get_ledger_commit_progress(&self) -> Result { - get_progress(&self.db, &DbMetadataKey::LedgerCommitProgress)?.ok_or(AptosDbError::NotFound( - "No LedgerCommitProgress in db.".to_string(), - )) + get_progress(&self.db, &DbMetadataKey::LedgerCommitProgress)? + .ok_or_else(|| AptosDbError::NotFound("No LedgerCommitProgress in db.".to_string())) } pub(crate) fn get_pruner_progress(&self) -> Result { - get_progress(&self.db, &DbMetadataKey::LedgerPrunerProgress)?.ok_or(AptosDbError::NotFound( - "No LedgerPrunerProgress in db.".to_string(), - )) + get_progress(&self.db, &DbMetadataKey::LedgerPrunerProgress)? + .ok_or_else(|| AptosDbError::NotFound("No LedgerPrunerProgress in db.".to_string())) } } @@ -137,7 +135,7 @@ impl LedgerMetadataDb { /// Returns the latest ledger info, or NOT_FOUND if it doesn't exist. pub(crate) fn get_latest_ledger_info(&self) -> Result { self.get_latest_ledger_info_option() - .ok_or(AptosDbError::NotFound(String::from("Genesis LedgerInfo"))) + .ok_or_else(|| AptosDbError::NotFound(String::from("Genesis LedgerInfo"))) } /// Returns the latest ledger info for a given epoch. @@ -147,9 +145,7 @@ impl LedgerMetadataDb { ) -> Result { self.db .get::(&epoch)? - .ok_or(AptosDbError::NotFound(format!( - "Last LedgerInfo of epoch {epoch}" - ))) + .ok_or_else(|| AptosDbError::NotFound(format!("Last LedgerInfo of epoch {epoch}"))) } /// Returns an iterator that yields epoch ending ledger infos, starting from `start_epoch`, and @@ -304,9 +300,10 @@ impl LedgerMetadataDb { let mut iter = self.db.iter::()?; iter.seek_for_prev(&version)?; - let (_, block_height) = iter.next().transpose()?.ok_or(anyhow!( - "Block is not found at version {version}, maybe pruned?" - ))?; + let (_, block_height) = iter + .next() + .transpose()? + .ok_or_else(|| anyhow!("Block is not found at version {version}, maybe pruned?"))?; Ok(block_height) } @@ -320,7 +317,7 @@ impl LedgerMetadataDb { let (block_version, block_height) = iter .next() .transpose()? - .ok_or(anyhow!("Block is not found at or after version {version}"))?; + .ok_or_else(|| anyhow!("Block is not found at or after version {version}"))?; Ok((block_version, block_height)) } diff --git a/storage/aptosdb/src/ledger_db/write_set_db.rs b/storage/aptosdb/src/ledger_db/write_set_db.rs index 92dbc1e654178..9320e6fb5b19a 100644 --- a/storage/aptosdb/src/ledger_db/write_set_db.rs +++ b/storage/aptosdb/src/ledger_db/write_set_db.rs @@ -54,10 +54,7 @@ impl WriteSetDb { pub(crate) fn get_write_set(&self, version: Version) -> Result { self.db .get::(&version)? - .ok_or(AptosDbError::NotFound(format!( - "WriteSet at version {}", - version - ))) + .ok_or_else(|| AptosDbError::NotFound(format!("WriteSet at version {}", version))) } /// Returns an iterator that yields `num_transactions` write sets starting from `start_version`. diff --git a/storage/backup/backup-cli/src/metadata/view.rs b/storage/backup/backup-cli/src/metadata/view.rs index 3b857651208de..70439943c726e 100644 --- a/storage/backup/backup-cli/src/metadata/view.rs +++ b/storage/backup/backup-cli/src/metadata/view.rs @@ -259,10 +259,10 @@ impl fmt::Display for BackupStorageState { write!( f, "latest_epoch_ending_epoch: {}, latest_state_snapshot_epoch: {}, latest_state_snapshot_version: {}, latest_transaction_version: {}", - self.latest_epoch_ending_epoch.as_ref().map_or("none".to_string(), u64::to_string), - self.latest_state_snapshot_epoch.as_ref().map_or("none".to_string(), u64::to_string), - self.latest_state_snapshot_version.as_ref().map_or("none".to_string(), Version::to_string), - self.latest_transaction_version.as_ref().map_or("none".to_string(), Version::to_string), + self.latest_epoch_ending_epoch.as_ref().map_or_else(|| "none".to_string(), u64::to_string), + self.latest_state_snapshot_epoch.as_ref().map_or_else(|| "none".to_string(), u64::to_string), + self.latest_state_snapshot_version.as_ref().map_or_else(|| "none".to_string(), Version::to_string), + self.latest_transaction_version.as_ref().map_or_else(|| "none".to_string(), Version::to_string), ) } } diff --git a/third_party/move/move-prover/lab/src/benchmark.rs b/third_party/move/move-prover/lab/src/benchmark.rs index 957352c6a537b..6e4ba638f8bca 100644 --- a/third_party/move/move-prover/lab/src/benchmark.rs +++ b/third_party/move/move-prover/lab/src/benchmark.rs @@ -98,7 +98,7 @@ pub fn benchmark(args: &[String]) { let matches = cmd_line_parser.get_matches_from(args); let get_vec = |s: &str| -> Vec { let vs = matches.get_many::(s); - vs.map_or(vec![], |v| v.cloned().collect()) + vs.map_or_else(Vec::new, |v| v.cloned().collect()) }; let sources = get_vec("sources"); let deps = get_vec("dependencies"); diff --git a/third_party/move/move-prover/lab/src/plot.rs b/third_party/move/move-prover/lab/src/plot.rs index 7464c7d3d9b74..32d71bb3374c4 100644 --- a/third_party/move/move-prover/lab/src/plot.rs +++ b/third_party/move/move-prover/lab/src/plot.rs @@ -70,7 +70,7 @@ pub fn plot_svg(args: &[String]) -> anyhow::Result<()> { }; let out_file = matches .get_one::("out") - .map_or("plot.svg".to_owned(), |s| s.clone()); + .map_or_else(|| "plot.svg".to_owned(), |s| s.clone()); let sort = matches.contains_id("sort"); let top = matches.get_one::("top"); let data_files = get_vec("data-files"); diff --git a/third_party/move/tools/move-package/src/compilation/compiled_package.rs b/third_party/move/tools/move-package/src/compilation/compiled_package.rs index deb21b8fb93ac..95b160e50a365 100644 --- a/third_party/move/tools/move-package/src/compilation/compiled_package.rs +++ b/third_party/move/tools/move-package/src/compilation/compiled_package.rs @@ -712,7 +712,7 @@ impl CompiledPackage { for annot_unit in all_compiled_units { let source_path_str = file_map .get(&annot_unit.loc().file_hash()) - .ok_or(anyhow::anyhow!("invalid transaction script bytecode"))? + .ok_or_else(|| anyhow::anyhow!("invalid transaction script bytecode"))? .0 .as_str(); let source_path = PathBuf::from(source_path_str); diff --git a/types/src/block_info.rs b/types/src/block_info.rs index 62e6e8d51254d..1bf7b2bd33b2f 100644 --- a/types/src/block_info.rs +++ b/types/src/block_info.rs @@ -143,7 +143,7 @@ impl BlockInfo { /// The epoch after this block committed pub fn next_block_epoch(&self) -> u64 { - self.next_epoch_state().map_or(self.epoch(), |e| e.epoch) + self.next_epoch_state().map_or(self.epoch, |e| e.epoch) } pub fn change_timestamp(&mut self, timestamp: u64) { @@ -231,7 +231,7 @@ impl Display for BlockInfo { self.executed_state_id(), self.version(), self.timestamp_usecs(), - self.next_epoch_state.as_ref().map_or("None".to_string(), |epoch_state| format!("{}", epoch_state)), + self.next_epoch_state.as_ref().map_or_else(|| "None".to_string(), |epoch_state| format!("{}", epoch_state)), ) } }