From f684dd4c4cebc9f0d0b6b1402530d45ae952e7f3 Mon Sep 17 00:00:00 2001 From: Delweng Date: Mon, 14 Oct 2024 23:45:26 +0800 Subject: [PATCH] chore(clippy): enable if_then_some_else_none lint (#11679) Signed-off-by: jsvisa Co-authored-by: Matthias Seitz --- Cargo.toml | 1 + crates/chainspec/src/spec.rs | 7 ++-- crates/consensus/auto-seal/src/lib.rs | 32 +++++++------------ crates/engine/local/src/miner.rs | 10 +++--- crates/engine/local/src/payload.rs | 18 +++++------ crates/ethereum/evm/src/lib.rs | 11 ++----- crates/net/network/src/cache.rs | 2 +- crates/net/p2p/src/test_utils/full_block.rs | 18 +++++------ crates/node/core/src/args/log.rs | 2 +- crates/optimism/evm/src/lib.rs | 11 ++----- .../src/segments/user/receipts_by_logs.rs | 6 +--- .../rpc-eth-api/src/helpers/pending_block.rs | 2 +- crates/storage/db-models/src/accounts.rs | 8 ++--- .../storage/db/src/implementation/mdbx/mod.rs | 7 ++-- .../src/providers/database/provider.rs | 14 ++++---- .../src/providers/static_file/manager.rs | 2 +- .../src/providers/static_file/writer.rs | 20 ++++++------ .../storage/provider/src/test_utils/mock.rs | 15 ++------- crates/transaction-pool/src/maintain.rs | 9 +++--- crates/trie/common/src/subnode.rs | 10 +++--- crates/trie/trie/src/trie_cursor/subnode.rs | 2 +- crates/trie/trie/src/witness.rs | 15 ++++----- 22 files changed, 87 insertions(+), 135 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 628d7d47b..ac0ab2d39 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -186,6 +186,7 @@ explicit_iter_loop = "warn" flat_map_option = "warn" from_iter_instead_of_collect = "warn" if_not_else = "warn" +if_then_some_else_none = "warn" implicit_clone = "warn" imprecise_flops = "warn" iter_on_empty_collections = "warn" diff --git a/crates/chainspec/src/spec.rs b/crates/chainspec/src/spec.rs index f80a20924..e43e0bc78 100644 --- a/crates/chainspec/src/spec.rs +++ b/crates/chainspec/src/spec.rs @@ -297,11 +297,8 @@ impl ChainSpec { }; // If Prague is activated at genesis we set requests root to an empty trie root. - let requests_root = if self.is_prague_active_at_timestamp(self.genesis.timestamp) { - Some(EMPTY_ROOT_HASH) - } else { - None - }; + let requests_root = + self.is_prague_active_at_timestamp(self.genesis.timestamp).then_some(EMPTY_ROOT_HASH); Header { gas_limit: self.genesis.gas_limit, diff --git a/crates/consensus/auto-seal/src/lib.rs b/crates/consensus/auto-seal/src/lib.rs index f1ef64c8c..261227f10 100644 --- a/crates/consensus/auto-seal/src/lib.rs +++ b/crates/consensus/auto-seal/src/lib.rs @@ -282,17 +282,13 @@ impl StorageInner { parent.next_block_base_fee(chain_spec.base_fee_params_at_timestamp(timestamp)) }); - let blob_gas_used = if chain_spec.is_cancun_active_at_timestamp(timestamp) { - let mut sum_blob_gas_used = 0; - for tx in transactions { - if let Some(blob_tx) = tx.transaction.as_eip4844() { - sum_blob_gas_used += blob_tx.blob_gas(); - } - } - Some(sum_blob_gas_used) - } else { - None - }; + let blob_gas_used = chain_spec.is_cancun_active_at_timestamp(timestamp).then(|| { + transactions + .iter() + .filter_map(|tx| tx.transaction.as_eip4844()) + .map(|blob_tx| blob_tx.blob_gas()) + .sum::() + }); let mut header = Header { parent_hash: self.best_hash, @@ -304,7 +300,7 @@ impl StorageInner { gas_limit: chain_spec.max_gas_limit(), timestamp, base_fee_per_gas, - blob_gas_used: blob_gas_used.map(Into::into), + blob_gas_used, requests_root: requests.map(|r| proofs::calculate_requests_root(&r.0)), ..Default::default() }; @@ -316,14 +312,10 @@ impl StorageInner { header.blob_gas_used = Some(0); let (parent_excess_blob_gas, parent_blob_gas_used) = match parent { - Some(parent_block) - if chain_spec.is_cancun_active_at_timestamp(parent_block.timestamp) => - { - ( - parent_block.excess_blob_gas.unwrap_or_default(), - parent_block.blob_gas_used.unwrap_or_default(), - ) - } + Some(parent) if chain_spec.is_cancun_active_at_timestamp(parent.timestamp) => ( + parent.excess_blob_gas.unwrap_or_default(), + parent.blob_gas_used.unwrap_or_default(), + ), _ => (0, 0), }; header.excess_blob_gas = diff --git a/crates/engine/local/src/miner.rs b/crates/engine/local/src/miner.rs index e12a2a50d..f20d70b14 100644 --- a/crates/engine/local/src/miner.rs +++ b/crates/engine/local/src/miner.rs @@ -212,14 +212,12 @@ where let block = payload.block(); let cancun_fields = - if self.provider.chain_spec().is_cancun_active_at_timestamp(block.timestamp) { - Some(CancunPayloadFields { + self.provider.chain_spec().is_cancun_active_at_timestamp(block.timestamp).then(|| { + CancunPayloadFields { parent_beacon_block_root: block.parent_beacon_block_root.unwrap(), versioned_hashes: block.blob_versioned_hashes().into_iter().copied().collect(), - }) - } else { - None - }; + } + }); let (tx, rx) = oneshot::channel(); self.to_engine.send(BeaconEngineMessage::NewPayload { diff --git a/crates/engine/local/src/payload.rs b/crates/engine/local/src/payload.rs index 15d5ff2cf..5111360d5 100644 --- a/crates/engine/local/src/payload.rs +++ b/crates/engine/local/src/payload.rs @@ -31,16 +31,14 @@ where timestamp, prev_randao: B256::random(), suggested_fee_recipient: Address::random(), - withdrawals: if self.chain_spec.is_shanghai_active_at_timestamp(timestamp) { - Some(Default::default()) - } else { - None - }, - parent_beacon_block_root: if self.chain_spec.is_cancun_active_at_timestamp(timestamp) { - Some(B256::random()) - } else { - None - }, + withdrawals: self + .chain_spec + .is_shanghai_active_at_timestamp(timestamp) + .then(Default::default), + parent_beacon_block_root: self + .chain_spec + .is_cancun_active_at_timestamp(timestamp) + .then(B256::random), } } } diff --git a/crates/ethereum/evm/src/lib.rs b/crates/ethereum/evm/src/lib.rs index a71f26f70..8ea39f93d 100644 --- a/crates/ethereum/evm/src/lib.rs +++ b/crates/ethereum/evm/src/lib.rs @@ -134,17 +134,10 @@ impl ConfigureEvmEnv for EthEvmConfig { let spec_id = revm_spec_by_timestamp_after_merge(&self.chain_spec, attributes.timestamp); // if the parent block did not have excess blob gas (i.e. it was pre-cancun), but it is - // cancun now, we need to set the excess blob gas to the default value + // cancun now, we need to set the excess blob gas to the default value(0) let blob_excess_gas_and_price = parent .next_block_excess_blob_gas() - .or_else(|| { - if spec_id == SpecId::CANCUN { - // default excess blob gas is zero - Some(0) - } else { - None - } - }) + .or_else(|| (spec_id == SpecId::CANCUN).then_some(0)) .map(BlobExcessGasAndPrice::new); let mut basefee = parent.next_block_base_fee( diff --git a/crates/net/network/src/cache.rs b/crates/net/network/src/cache.rs index fb2daca66..758b49167 100644 --- a/crates/net/network/src/cache.rs +++ b/crates/net/network/src/cache.rs @@ -42,7 +42,7 @@ impl LruCache { pub fn insert_and_get_evicted(&mut self, entry: T) -> (bool, Option) { let new = self.inner.peek(&entry).is_none(); let evicted = - if new && (self.limit as usize) <= self.inner.len() { self.remove_lru() } else { None }; + (new && (self.limit as usize) <= self.inner.len()).then(|| self.remove_lru()).flatten(); _ = self.inner.get_or_insert(entry, || ()); (new, evicted) diff --git a/crates/net/p2p/src/test_utils/full_block.rs b/crates/net/p2p/src/test_utils/full_block.rs index acc01a60e..8a13f6932 100644 --- a/crates/net/p2p/src/test_utils/full_block.rs +++ b/crates/net/p2p/src/test_utils/full_block.rs @@ -185,15 +185,15 @@ impl HeadersClient for TestFullBlockClient { .filter_map(|_| { headers.iter().find_map(|(hash, header)| { // Checks if the header matches the specified block or number. - if BlockNumHash::new(header.number, *hash).matches_block_or_num(&block) { - match request.direction { - HeadersDirection::Falling => block = header.parent_hash.into(), - HeadersDirection::Rising => block = (header.number + 1).into(), - } - Some(header.clone()) - } else { - None - } + BlockNumHash::new(header.number, *hash).matches_block_or_num(&block).then( + || { + match request.direction { + HeadersDirection::Falling => block = header.parent_hash.into(), + HeadersDirection::Rising => block = (header.number + 1).into(), + } + header.clone() + }, + ) }) }) .collect::>(); diff --git a/crates/node/core/src/args/log.rs b/crates/node/core/src/args/log.rs index aa2e0cf5f..3d124fba2 100644 --- a/crates/node/core/src/args/log.rs +++ b/crates/node/core/src/args/log.rs @@ -78,7 +78,7 @@ impl LogArgs { format, self.verbosity.directive().to_string(), filter, - if use_color { Some(self.color.to_string()) } else { None }, + use_color.then(|| self.color.to_string()), ) } diff --git a/crates/optimism/evm/src/lib.rs b/crates/optimism/evm/src/lib.rs index b220b6056..158ed2e89 100644 --- a/crates/optimism/evm/src/lib.rs +++ b/crates/optimism/evm/src/lib.rs @@ -139,17 +139,10 @@ impl ConfigureEvmEnv for OptimismEvmConfig { let spec_id = revm_spec_by_timestamp_after_bedrock(&self.chain_spec, attributes.timestamp); // if the parent block did not have excess blob gas (i.e. it was pre-cancun), but it is - // cancun now, we need to set the excess blob gas to the default value + // cancun now, we need to set the excess blob gas to the default value(0) let blob_excess_gas_and_price = parent .next_block_excess_blob_gas() - .or_else(|| { - if spec_id.is_enabled_in(SpecId::CANCUN) { - // default excess blob gas is zero - Some(0) - } else { - None - } - }) + .or_else(|| (spec_id.is_enabled_in(SpecId::CANCUN)).then_some(0)) .map(BlobExcessGasAndPrice::new); let block_env = BlockEnv { diff --git a/crates/prune/prune/src/segments/user/receipts_by_logs.rs b/crates/prune/prune/src/segments/user/receipts_by_logs.rs index 489df7e72..05bc40b6c 100644 --- a/crates/prune/prune/src/segments/user/receipts_by_logs.rs +++ b/crates/prune/prune/src/segments/user/receipts_by_logs.rs @@ -267,11 +267,7 @@ mod tests { let mut receipt = random_receipt(&mut rng, transaction, Some(1)); receipt.logs.push(random_log( &mut rng, - if txi == (block.body.transactions.len() - 1) { - Some(deposit_contract_addr) - } else { - None - }, + (txi == (block.body.transactions.len() - 1)).then_some(deposit_contract_addr), Some(1), )); receipts.push((receipts.len() as u64, receipt)); diff --git a/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs b/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs index 03597289f..85ad7fd18 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs @@ -415,7 +415,7 @@ pub trait LoadPendingBlock: EthApiTypes { // check if cancun is activated to set eip4844 header fields correctly let blob_gas_used = - if cfg.handler_cfg.spec_id >= SpecId::CANCUN { Some(sum_blob_gas_used) } else { None }; + (cfg.handler_cfg.spec_id >= SpecId::CANCUN).then_some(sum_blob_gas_used); // note(onbjerg): the rpc spec has not been changed to include requests, so for now we just // set these to empty diff --git a/crates/storage/db-models/src/accounts.rs b/crates/storage/db-models/src/accounts.rs index e1f477396..b0099d22d 100644 --- a/crates/storage/db-models/src/accounts.rs +++ b/crates/storage/db-models/src/accounts.rs @@ -39,13 +39,11 @@ impl Compact for AccountBeforeTx { let address = Address::from_slice(&buf[..20]); buf.advance(20); - let info = if len - 20 > 0 { + let info = (len - 20 > 0).then(|| { let (acc, advanced_buf) = Account::from_compact(buf, len - 20); buf = advanced_buf; - Some(acc) - } else { - None - }; + acc + }); (Self { address, info }, buf) } diff --git a/crates/storage/db/src/implementation/mdbx/mod.rs b/crates/storage/db/src/implementation/mdbx/mod.rs index 1deb86ba6..65b804e6a 100644 --- a/crates/storage/db/src/implementation/mdbx/mod.rs +++ b/crates/storage/db/src/implementation/mdbx/mod.rs @@ -256,10 +256,9 @@ impl DatabaseEnv { args: DatabaseArguments, ) -> Result { let _lock_file = if kind.is_rw() { - Some( - StorageLock::try_acquire(path) - .map_err(|err| DatabaseError::Other(err.to_string()))?, - ) + StorageLock::try_acquire(path) + .map_err(|err| DatabaseError::Other(err.to_string()))? + .into() } else { None }; diff --git a/crates/storage/provider/src/providers/database/provider.rs b/crates/storage/provider/src/providers/database/provider.rs index 33fed1e80..3b074a5af 100644 --- a/crates/storage/provider/src/providers/database/provider.rs +++ b/crates/storage/provider/src/providers/database/provider.rs @@ -542,18 +542,18 @@ impl DatabaseProvider { // even if empty let withdrawals = if self.chain_spec.is_shanghai_active_at_timestamp(header_ref.timestamp) { - Some( - withdrawals_cursor - .seek_exact(header_ref.number)? - .map(|(_, w)| w.withdrawals) - .unwrap_or_default(), - ) + withdrawals_cursor + .seek_exact(header_ref.number)? + .map(|(_, w)| w.withdrawals) + .unwrap_or_default() + .into() } else { None }; let requests = if self.chain_spec.is_prague_active_at_timestamp(header_ref.timestamp) { - Some(requests_cursor.seek_exact(header_ref.number)?.unwrap_or_default().1) + (requests_cursor.seek_exact(header_ref.number)?.unwrap_or_default().1) + .into() } else { None }; diff --git a/crates/storage/provider/src/providers/static_file/manager.rs b/crates/storage/provider/src/providers/static_file/manager.rs index ec76e9504..e233332a0 100644 --- a/crates/storage/provider/src/providers/static_file/manager.rs +++ b/crates/storage/provider/src/providers/static_file/manager.rs @@ -222,7 +222,7 @@ impl StaticFileProviderInner { /// Creates a new [`StaticFileProviderInner`]. fn new(path: impl AsRef, access: StaticFileAccess) -> ProviderResult { let _lock_file = if access.is_read_write() { - Some(StorageLock::try_acquire(path.as_ref())?) + StorageLock::try_acquire(path.as_ref())?.into() } else { None }; diff --git a/crates/storage/provider/src/providers/static_file/writer.rs b/crates/storage/provider/src/providers/static_file/writer.rs index 3858f1b14..8c31c021f 100644 --- a/crates/storage/provider/src/providers/static_file/writer.rs +++ b/crates/storage/provider/src/providers/static_file/writer.rs @@ -289,16 +289,16 @@ impl StaticFileProviderRW { // // If that expected block start is 0, then it means that there's no actual block data, and // there's no block data in static files. - let segment_max_block = match self.writer.user_header().block_range() { - Some(block_range) => Some(block_range.end()), - None => { - if self.writer.user_header().expected_block_start() > 0 { - Some(self.writer.user_header().expected_block_start() - 1) - } else { - None - } - } - }; + let segment_max_block = self + .writer + .user_header() + .block_range() + .as_ref() + .map(|block_range| block_range.end()) + .or_else(|| { + (self.writer.user_header().expected_block_start() > 0) + .then(|| self.writer.user_header().expected_block_start() - 1) + }); self.reader().update_index(self.writer.user_header().segment(), segment_max_block) } diff --git a/crates/storage/provider/src/test_utils/mock.rs b/crates/storage/provider/src/test_utils/mock.rs index 3325d3ae9..c7c94b939 100644 --- a/crates/storage/provider/src/test_utils/mock.rs +++ b/crates/storage/provider/src/test_utils/mock.rs @@ -344,13 +344,8 @@ impl TransactionsProvider for MockEthProvider { .values() .flat_map(|block| &block.body.transactions) .enumerate() - .filter_map(|(tx_number, tx)| { - if range.contains(&(tx_number as TxNumber)) { - Some(tx.clone().into()) - } else { - None - } - }) + .filter(|&(tx_number, _)| range.contains(&(tx_number as TxNumber))) + .map(|(_, tx)| tx.clone().into()) .collect(); Ok(transactions) @@ -366,11 +361,7 @@ impl TransactionsProvider for MockEthProvider { .flat_map(|block| &block.body.transactions) .enumerate() .filter_map(|(tx_number, tx)| { - if range.contains(&(tx_number as TxNumber)) { - Some(tx.recover_signer()?) - } else { - None - } + range.contains(&(tx_number as TxNumber)).then(|| tx.recover_signer()).flatten() }) .collect(); diff --git a/crates/transaction-pool/src/maintain.rs b/crates/transaction-pool/src/maintain.rs index aaf2d6d12..23a8d0dc6 100644 --- a/crates/transaction-pool/src/maintain.rs +++ b/crates/transaction-pool/src/maintain.rs @@ -455,11 +455,10 @@ impl FinalizedBlockTracker { /// Updates the tracked finalized block and returns the new finalized block if it changed fn update(&mut self, finalized_block: Option) -> Option { let finalized = finalized_block?; - if self.last_finalized_block.replace(finalized).map_or(true, |last| last < finalized) { - Some(finalized) - } else { - None - } + self.last_finalized_block + .replace(finalized) + .map_or(true, |last| last < finalized) + .then_some(finalized) } } diff --git a/crates/trie/common/src/subnode.rs b/crates/trie/common/src/subnode.rs index 98ce76a32..c64b2317c 100644 --- a/crates/trie/common/src/subnode.rs +++ b/crates/trie/common/src/subnode.rs @@ -51,16 +51,14 @@ impl Compact for StoredSubNode { buf.advance(key_len); let nibbles_exists = buf.get_u8() != 0; - let nibble = if nibbles_exists { Some(buf.get_u8()) } else { None }; + let nibble = nibbles_exists.then(|| buf.get_u8()); let node_exists = buf.get_u8() != 0; - let node = if node_exists { + let node = node_exists.then(|| { let (node, rest) = BranchNodeCompact::from_compact(buf, 0); buf = rest; - Some(node) - } else { - None - }; + node + }); (Self { key, nibble, node }, buf) } diff --git a/crates/trie/trie/src/trie_cursor/subnode.rs b/crates/trie/trie/src/trie_cursor/subnode.rs index c2ba839eb..9d5a2770b 100644 --- a/crates/trie/trie/src/trie_cursor/subnode.rs +++ b/crates/trie/trie/src/trie_cursor/subnode.rs @@ -49,7 +49,7 @@ impl From for CursorSubNode { impl From for StoredSubNode { fn from(value: CursorSubNode) -> Self { - let nibble = if value.nibble >= 0 { Some(value.nibble as u8) } else { None }; + let nibble = (value.nibble >= 0).then_some(value.nibble as u8); Self { key: value.key.to_vec(), nibble, node: value.node } } } diff --git a/crates/trie/trie/src/witness.rs b/crates/trie/trie/src/witness.rs index c042a0d82..582319c7f 100644 --- a/crates/trie/trie/src/witness.rs +++ b/crates/trie/trie/src/witness.rs @@ -111,14 +111,13 @@ where .accounts .get(&hashed_address) .ok_or(TrieWitnessError::MissingAccount(hashed_address))?; - let value = if account.is_some() || storage_multiproof.root != EMPTY_ROOT_HASH { - account_rlp.clear(); - TrieAccount::from((account.unwrap_or_default(), storage_multiproof.root)) - .encode(&mut account_rlp as &mut dyn BufMut); - Some(account_rlp.clone()) - } else { - None - }; + let value = + (account.is_some() || storage_multiproof.root != EMPTY_ROOT_HASH).then(|| { + account_rlp.clear(); + TrieAccount::from((account.unwrap_or_default(), storage_multiproof.root)) + .encode(&mut account_rlp as &mut dyn BufMut); + account_rlp.clone() + }); let key = Nibbles::unpack(hashed_address); account_trie_nodes.extend( self.target_nodes(