From 5ac2619868a2ff1d2420129213672217be6aa4c2 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 | 15 ++++++----- .../src/txn_last_input_output.rs | 23 +++++++++-------- .../natives/aggregator_natives/helpers_v1.rs | 20 +++++++-------- .../mvhashmap/src/versioned_group_data.rs | 2 +- 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 | 17 +++++++------ .../src/input_processing/witness_gen.rs | 4 ++- mempool/src/core_mempool/mempool.rs | 9 +++---- 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 +--- storage/aptosdb/src/state_store/mod.rs | 21 +++++++++------- .../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 +- third_party/move/move-prover/src/lib.rs | 7 +++--- .../src/compilation/compiled_package.rs | 2 +- types/src/block_info.rs | 5 ++-- types/src/proof/definition.rs | 2 +- types/src/state_store/state_key/mod.rs | 4 +-- 38 files changed, 164 insertions(+), 146 deletions(-) diff --git a/api/src/context.rs b/api/src/context.rs index 4cea588b9906a..98c03eebf3482 100644 --- a/api/src/context.rs +++ b/api/src/context.rs @@ -832,7 +832,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) })? @@ -931,7 +931,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 cde73c85b7992..143f288149ba7 100644 --- a/aptos-move/block-executor/src/executor.rs +++ b/aptos-move/block-executor/src/executor.rs @@ -116,13 +116,16 @@ where let sync_view = LatestView::new(base_view, ViewState::Sync(parallel_state), idx_to_execute); 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()); + let mut prev_modified_keys = match last_input_output.modified_keys(idx_to_execute) { + Some(keys) => keys.collect(), + None => HashMap::new(), + }; - let mut prev_modified_delayed_fields = last_input_output - .delayed_field_keys(idx_to_execute) - .map_or(HashSet::new(), |keys| keys.collect()); + let mut prev_modified_delayed_fields = + match last_input_output.delayed_field_keys(idx_to_execute) { + Some(keys) => keys.collect(), + None => HashSet::new(), + }; let mut read_set = sync_view.take_parallel_reads(); 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 c928a88005bac..fb1778936d673 100644 --- a/aptos-move/block-executor/src/txn_last_input_output.rs +++ b/aptos-move/block-executor/src/txn_last_input_output.rs @@ -34,12 +34,15 @@ 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() { - ExecutionStatus::Success(t) | ExecutionStatus::SkipRest(t) => t.$f(), - ExecutionStatus::Abort(_) - | ExecutionStatus::SpeculativeExecutionAbortError(_) - | ExecutionStatus::DelayedFieldsCodeInvariantError(_) => vec![], - }) + .map_or_else( + || vec![], + |txn_output| match txn_output.as_ref() { + ExecutionStatus::Success(t) | ExecutionStatus::SkipRest(t) => t.$f(), + ExecutionStatus::Abort(_) + | ExecutionStatus::SpeculativeExecutionAbortError(_) + | ExecutionStatus::DelayedFieldsCodeInvariantError(_) => vec![], + }, + ) }}; } @@ -353,9 +356,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()) @@ -366,7 +369,7 @@ impl, E: Debug + Send + Clone> Box::new(empty::<(T::Event, Option)>()) }, }, - ) + } } pub(crate) fn record_finalized_group( 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/aptos-move/mvhashmap/src/versioned_group_data.rs b/aptos-move/mvhashmap/src/versioned_group_data.rs index bf728828d64d6..ace2bbef784e8 100644 --- a/aptos-move/mvhashmap/src/versioned_group_data.rs +++ b/aptos-move/mvhashmap/src/versioned_group_data.rs @@ -337,7 +337,7 @@ impl VersionedGro self.versioned_map .get(tag) - .ok_or(common_error()) + .ok_or_else(common_error) .and_then(|tree| { match tree .range(ShiftedTxnIndex::zero_idx()..ShiftedTxnIndex::new(txn_idx)) 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 f4eddf3d50ccf..062fe976a0501 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 0dc03ab88d105..445556314c180 100644 --- a/consensus/src/liveness/round_state.rs +++ b/consensus/src/liveness/round_state.rs @@ -337,7 +337,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 a6aecbd9d61d5..0f65d59d244c4 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 1f7ca3cfaa6b2..3415747e050bd 100644 --- a/crates/aptos/src/move_tool/mod.rs +++ b/crates/aptos/src/move_tool/mod.rs @@ -1569,13 +1569,16 @@ 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| { - if success { - "Success".to_string() - } else { - "Failed".to_string() - } - }); + let status = tx_summary.success.map_or_else( + || "".to_string(), + |success| { + if success { + "Success".to_string() + } else { + "Failed".to_string() + } + }, + ); println!("Transaction executed: {} ({})\n", status, &tx_hash); tx_hashes.push(tx_hash); publishing_result = Ok(tx_summary); 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/core_mempool/mempool.rs b/mempool/src/core_mempool/mempool.rs index bf6d52a462aa0..eed43649a2831 100644 --- a/mempool/src/core_mempool/mempool.rs +++ b/mempool/src/core_mempool/mempool.rs @@ -211,11 +211,10 @@ impl Mempool { ); if insertion_info.park_time.is_none() { - let use_case_label = tracked_use_case - .as_ref() - .map_or("entry_user_other", |(_, use_case_name)| { - use_case_name.as_str() - }); + let use_case_label = tracked_use_case.as_ref().map_or_else( + || "entry_user_other", + |(_, use_case_name)| use_case_name.as_str(), + ); counters::TXN_E2E_USE_CASE_COMMIT_LATENCY .with_label_values(&[ 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 5556d8a41d6f1..fe90455ddc77a 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), @@ -246,9 +249,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/aptosdb/src/state_store/mod.rs b/storage/aptosdb/src/state_store/mod.rs index 1b30c6343eb89..da185ce5cf049 100644 --- a/storage/aptosdb/src/state_store/mod.rs +++ b/storage/aptosdb/src/state_store/mod.rs @@ -191,15 +191,18 @@ impl DbReader for StateDb { } fn get_state_storage_usage(&self, version: Option) -> Result { - version.map_or(Ok(StateStorageUsage::zero()), |version| { - Ok(match self.ledger_db.metadata_db().get_usage(version) { - Ok(data) => data, - _ => { - ensure!(self.skip_usage, "VersionData at {version} is missing."); - StateStorageUsage::new_untracked() - }, - }) - }) + version.map_or_else( + || Ok(StateStorageUsage::zero()), + |version| { + Ok(match self.ledger_db.metadata_db().get_usage(version) { + Ok(data) => data, + _ => { + ensure!(self.skip_usage, "VersionData at {version} is missing."); + StateStorageUsage::new_untracked() + }, + }) + }, + ) } } 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..9753018ba3511 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(vec![], |vs| vs.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/move-prover/src/lib.rs b/third_party/move/move-prover/src/lib.rs index d029e05e1767e..5742be82003fd 100644 --- a/third_party/move/move-prover/src/lib.rs +++ b/third_party/move/move-prover/src/lib.rs @@ -280,9 +280,10 @@ pub fn create_and_process_bytecode(options: &Options, env: &GlobalEnv) -> Functi let output_dir = Path::new(&options.output_path) .parent() .expect("expect the parent directory of the output path to exist"); - let output_prefix = options.move_sources.first().map_or("bytecode", |s| { - Path::new(s).file_name().unwrap().to_str().unwrap() - }); + let output_prefix = options.move_sources.first().map_or_else( + || "bytecode", + |s| Path::new(s).file_name().unwrap().to_str().unwrap(), + ); // Add function targets for all functions in the environment. for module_env in env.get_modules() { 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 97c13be3893f1..ca052b9cb13a8 100644 --- a/types/src/block_info.rs +++ b/types/src/block_info.rs @@ -139,7 +139,8 @@ 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_else(|| self.epoch, |e| e.epoch) } pub fn change_timestamp(&mut self, timestamp: u64) { @@ -227,7 +228,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)), ) } } diff --git a/types/src/proof/definition.rs b/types/src/proof/definition.rs index 15eb25d2adc50..9e80c43b39c41 100644 --- a/types/src/proof/definition.rs +++ b/types/src/proof/definition.rs @@ -397,7 +397,7 @@ impl SparseMerkleProof { let current_hash = self .leaf - .map_or(*SPARSE_MERKLE_PLACEHOLDER_HASH, |leaf| leaf.hash()); + .map_or_else(|| *SPARSE_MERKLE_PLACEHOLDER_HASH, |leaf| leaf.hash()); let actual_root_hash = self .siblings .iter() diff --git a/types/src/state_store/state_key/mod.rs b/types/src/state_store/state_key/mod.rs index 126936b74a507..fa126bb73572f 100644 --- a/types/src/state_store/state_key/mod.rs +++ b/types/src/state_store/state_key/mod.rs @@ -66,8 +66,8 @@ impl StateKey { return Err(StateKeyDecodeErr::EmptyInput); } let tag = val[0]; - let state_key_tag = - StateKeyTag::from_u8(tag).ok_or(StateKeyDecodeErr::UnknownTag { unknown_tag: tag })?; + let state_key_tag = StateKeyTag::from_u8(tag) + .ok_or_else(|| StateKeyDecodeErr::UnknownTag { unknown_tag: tag })?; let myself = match state_key_tag { StateKeyTag::AccessPath => { let AccessPath { address, path } = bcs::from_bytes(&val[1..])?;