chore(clippy): enable if_then_some_else_none lint (#11679)

Signed-off-by: jsvisa <delweng@gmail.com>
Co-authored-by: Matthias Seitz <matthias.seitz@outlook.de>
This commit is contained in:
Delweng
2024-10-14 23:45:26 +08:00
committed by GitHub
parent 523bfb9c81
commit f684dd4c4c
22 changed files with 87 additions and 135 deletions

View File

@ -186,6 +186,7 @@ explicit_iter_loop = "warn"
flat_map_option = "warn" flat_map_option = "warn"
from_iter_instead_of_collect = "warn" from_iter_instead_of_collect = "warn"
if_not_else = "warn" if_not_else = "warn"
if_then_some_else_none = "warn"
implicit_clone = "warn" implicit_clone = "warn"
imprecise_flops = "warn" imprecise_flops = "warn"
iter_on_empty_collections = "warn" iter_on_empty_collections = "warn"

View File

@ -297,11 +297,8 @@ impl ChainSpec {
}; };
// If Prague is activated at genesis we set requests root to an empty trie root. // 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) { let requests_root =
Some(EMPTY_ROOT_HASH) self.is_prague_active_at_timestamp(self.genesis.timestamp).then_some(EMPTY_ROOT_HASH);
} else {
None
};
Header { Header {
gas_limit: self.genesis.gas_limit, gas_limit: self.genesis.gas_limit,

View File

@ -282,17 +282,13 @@ impl StorageInner {
parent.next_block_base_fee(chain_spec.base_fee_params_at_timestamp(timestamp)) 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 blob_gas_used = chain_spec.is_cancun_active_at_timestamp(timestamp).then(|| {
let mut sum_blob_gas_used = 0; transactions
for tx in transactions { .iter()
if let Some(blob_tx) = tx.transaction.as_eip4844() { .filter_map(|tx| tx.transaction.as_eip4844())
sum_blob_gas_used += blob_tx.blob_gas(); .map(|blob_tx| blob_tx.blob_gas())
} .sum::<u64>()
} });
Some(sum_blob_gas_used)
} else {
None
};
let mut header = Header { let mut header = Header {
parent_hash: self.best_hash, parent_hash: self.best_hash,
@ -304,7 +300,7 @@ impl StorageInner {
gas_limit: chain_spec.max_gas_limit(), gas_limit: chain_spec.max_gas_limit(),
timestamp, timestamp,
base_fee_per_gas, 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)), requests_root: requests.map(|r| proofs::calculate_requests_root(&r.0)),
..Default::default() ..Default::default()
}; };
@ -316,14 +312,10 @@ impl StorageInner {
header.blob_gas_used = Some(0); header.blob_gas_used = Some(0);
let (parent_excess_blob_gas, parent_blob_gas_used) = match parent { let (parent_excess_blob_gas, parent_blob_gas_used) = match parent {
Some(parent_block) Some(parent) if chain_spec.is_cancun_active_at_timestamp(parent.timestamp) => (
if chain_spec.is_cancun_active_at_timestamp(parent_block.timestamp) => parent.excess_blob_gas.unwrap_or_default(),
{ parent.blob_gas_used.unwrap_or_default(),
( ),
parent_block.excess_blob_gas.unwrap_or_default(),
parent_block.blob_gas_used.unwrap_or_default(),
)
}
_ => (0, 0), _ => (0, 0),
}; };
header.excess_blob_gas = header.excess_blob_gas =

View File

@ -212,14 +212,12 @@ where
let block = payload.block(); let block = payload.block();
let cancun_fields = let cancun_fields =
if self.provider.chain_spec().is_cancun_active_at_timestamp(block.timestamp) { self.provider.chain_spec().is_cancun_active_at_timestamp(block.timestamp).then(|| {
Some(CancunPayloadFields { CancunPayloadFields {
parent_beacon_block_root: block.parent_beacon_block_root.unwrap(), parent_beacon_block_root: block.parent_beacon_block_root.unwrap(),
versioned_hashes: block.blob_versioned_hashes().into_iter().copied().collect(), versioned_hashes: block.blob_versioned_hashes().into_iter().copied().collect(),
}) }
} else { });
None
};
let (tx, rx) = oneshot::channel(); let (tx, rx) = oneshot::channel();
self.to_engine.send(BeaconEngineMessage::NewPayload { self.to_engine.send(BeaconEngineMessage::NewPayload {

View File

@ -31,16 +31,14 @@ where
timestamp, timestamp,
prev_randao: B256::random(), prev_randao: B256::random(),
suggested_fee_recipient: Address::random(), suggested_fee_recipient: Address::random(),
withdrawals: if self.chain_spec.is_shanghai_active_at_timestamp(timestamp) { withdrawals: self
Some(Default::default()) .chain_spec
} else { .is_shanghai_active_at_timestamp(timestamp)
None .then(Default::default),
}, parent_beacon_block_root: self
parent_beacon_block_root: if self.chain_spec.is_cancun_active_at_timestamp(timestamp) { .chain_spec
Some(B256::random()) .is_cancun_active_at_timestamp(timestamp)
} else { .then(B256::random),
None
},
} }
} }
} }

View File

@ -134,17 +134,10 @@ impl ConfigureEvmEnv for EthEvmConfig {
let spec_id = revm_spec_by_timestamp_after_merge(&self.chain_spec, attributes.timestamp); 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 // 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 let blob_excess_gas_and_price = parent
.next_block_excess_blob_gas() .next_block_excess_blob_gas()
.or_else(|| { .or_else(|| (spec_id == SpecId::CANCUN).then_some(0))
if spec_id == SpecId::CANCUN {
// default excess blob gas is zero
Some(0)
} else {
None
}
})
.map(BlobExcessGasAndPrice::new); .map(BlobExcessGasAndPrice::new);
let mut basefee = parent.next_block_base_fee( let mut basefee = parent.next_block_base_fee(

View File

@ -42,7 +42,7 @@ impl<T: Hash + Eq + fmt::Debug> LruCache<T> {
pub fn insert_and_get_evicted(&mut self, entry: T) -> (bool, Option<T>) { pub fn insert_and_get_evicted(&mut self, entry: T) -> (bool, Option<T>) {
let new = self.inner.peek(&entry).is_none(); let new = self.inner.peek(&entry).is_none();
let evicted = 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, || ()); _ = self.inner.get_or_insert(entry, || ());
(new, evicted) (new, evicted)

View File

@ -185,15 +185,15 @@ impl HeadersClient for TestFullBlockClient {
.filter_map(|_| { .filter_map(|_| {
headers.iter().find_map(|(hash, header)| { headers.iter().find_map(|(hash, header)| {
// Checks if the header matches the specified block or number. // Checks if the header matches the specified block or number.
if BlockNumHash::new(header.number, *hash).matches_block_or_num(&block) { BlockNumHash::new(header.number, *hash).matches_block_or_num(&block).then(
match request.direction { || {
HeadersDirection::Falling => block = header.parent_hash.into(), match request.direction {
HeadersDirection::Rising => block = (header.number + 1).into(), HeadersDirection::Falling => block = header.parent_hash.into(),
} HeadersDirection::Rising => block = (header.number + 1).into(),
Some(header.clone()) }
} else { header.clone()
None },
} )
}) })
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();

View File

@ -78,7 +78,7 @@ impl LogArgs {
format, format,
self.verbosity.directive().to_string(), self.verbosity.directive().to_string(),
filter, filter,
if use_color { Some(self.color.to_string()) } else { None }, use_color.then(|| self.color.to_string()),
) )
} }

View File

@ -139,17 +139,10 @@ impl ConfigureEvmEnv for OptimismEvmConfig {
let spec_id = revm_spec_by_timestamp_after_bedrock(&self.chain_spec, attributes.timestamp); 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 // 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 let blob_excess_gas_and_price = parent
.next_block_excess_blob_gas() .next_block_excess_blob_gas()
.or_else(|| { .or_else(|| (spec_id.is_enabled_in(SpecId::CANCUN)).then_some(0))
if spec_id.is_enabled_in(SpecId::CANCUN) {
// default excess blob gas is zero
Some(0)
} else {
None
}
})
.map(BlobExcessGasAndPrice::new); .map(BlobExcessGasAndPrice::new);
let block_env = BlockEnv { let block_env = BlockEnv {

View File

@ -267,11 +267,7 @@ mod tests {
let mut receipt = random_receipt(&mut rng, transaction, Some(1)); let mut receipt = random_receipt(&mut rng, transaction, Some(1));
receipt.logs.push(random_log( receipt.logs.push(random_log(
&mut rng, &mut rng,
if txi == (block.body.transactions.len() - 1) { (txi == (block.body.transactions.len() - 1)).then_some(deposit_contract_addr),
Some(deposit_contract_addr)
} else {
None
},
Some(1), Some(1),
)); ));
receipts.push((receipts.len() as u64, receipt)); receipts.push((receipts.len() as u64, receipt));

View File

@ -415,7 +415,7 @@ pub trait LoadPendingBlock: EthApiTypes {
// check if cancun is activated to set eip4844 header fields correctly // check if cancun is activated to set eip4844 header fields correctly
let blob_gas_used = 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 // note(onbjerg): the rpc spec has not been changed to include requests, so for now we just
// set these to empty // set these to empty

View File

@ -39,13 +39,11 @@ impl Compact for AccountBeforeTx {
let address = Address::from_slice(&buf[..20]); let address = Address::from_slice(&buf[..20]);
buf.advance(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); let (acc, advanced_buf) = Account::from_compact(buf, len - 20);
buf = advanced_buf; buf = advanced_buf;
Some(acc) acc
} else { });
None
};
(Self { address, info }, buf) (Self { address, info }, buf)
} }

View File

@ -256,10 +256,9 @@ impl DatabaseEnv {
args: DatabaseArguments, args: DatabaseArguments,
) -> Result<Self, DatabaseError> { ) -> Result<Self, DatabaseError> {
let _lock_file = if kind.is_rw() { let _lock_file = if kind.is_rw() {
Some( StorageLock::try_acquire(path)
StorageLock::try_acquire(path) .map_err(|err| DatabaseError::Other(err.to_string()))?
.map_err(|err| DatabaseError::Other(err.to_string()))?, .into()
)
} else { } else {
None None
}; };

View File

@ -542,18 +542,18 @@ impl<TX: DbTx, Spec: Send + Sync> DatabaseProvider<TX, Spec> {
// even if empty // even if empty
let withdrawals = let withdrawals =
if self.chain_spec.is_shanghai_active_at_timestamp(header_ref.timestamp) { if self.chain_spec.is_shanghai_active_at_timestamp(header_ref.timestamp) {
Some( withdrawals_cursor
withdrawals_cursor .seek_exact(header_ref.number)?
.seek_exact(header_ref.number)? .map(|(_, w)| w.withdrawals)
.map(|(_, w)| w.withdrawals) .unwrap_or_default()
.unwrap_or_default(), .into()
)
} else { } else {
None None
}; };
let requests = let requests =
if self.chain_spec.is_prague_active_at_timestamp(header_ref.timestamp) { 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 { } else {
None None
}; };

View File

@ -222,7 +222,7 @@ impl StaticFileProviderInner {
/// Creates a new [`StaticFileProviderInner`]. /// Creates a new [`StaticFileProviderInner`].
fn new(path: impl AsRef<Path>, access: StaticFileAccess) -> ProviderResult<Self> { fn new(path: impl AsRef<Path>, access: StaticFileAccess) -> ProviderResult<Self> {
let _lock_file = if access.is_read_write() { let _lock_file = if access.is_read_write() {
Some(StorageLock::try_acquire(path.as_ref())?) StorageLock::try_acquire(path.as_ref())?.into()
} else { } else {
None None
}; };

View File

@ -289,16 +289,16 @@ impl StaticFileProviderRW {
// //
// If that expected block start is 0, then it means that there's no actual block data, and // 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. // there's no block data in static files.
let segment_max_block = match self.writer.user_header().block_range() { let segment_max_block = self
Some(block_range) => Some(block_range.end()), .writer
None => { .user_header()
if self.writer.user_header().expected_block_start() > 0 { .block_range()
Some(self.writer.user_header().expected_block_start() - 1) .as_ref()
} else { .map(|block_range| block_range.end())
None .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) self.reader().update_index(self.writer.user_header().segment(), segment_max_block)
} }

View File

@ -344,13 +344,8 @@ impl TransactionsProvider for MockEthProvider {
.values() .values()
.flat_map(|block| &block.body.transactions) .flat_map(|block| &block.body.transactions)
.enumerate() .enumerate()
.filter_map(|(tx_number, tx)| { .filter(|&(tx_number, _)| range.contains(&(tx_number as TxNumber)))
if range.contains(&(tx_number as TxNumber)) { .map(|(_, tx)| tx.clone().into())
Some(tx.clone().into())
} else {
None
}
})
.collect(); .collect();
Ok(transactions) Ok(transactions)
@ -366,11 +361,7 @@ impl TransactionsProvider for MockEthProvider {
.flat_map(|block| &block.body.transactions) .flat_map(|block| &block.body.transactions)
.enumerate() .enumerate()
.filter_map(|(tx_number, tx)| { .filter_map(|(tx_number, tx)| {
if range.contains(&(tx_number as TxNumber)) { range.contains(&(tx_number as TxNumber)).then(|| tx.recover_signer()).flatten()
Some(tx.recover_signer()?)
} else {
None
}
}) })
.collect(); .collect();

View File

@ -455,11 +455,10 @@ impl FinalizedBlockTracker {
/// Updates the tracked finalized block and returns the new finalized block if it changed /// Updates the tracked finalized block and returns the new finalized block if it changed
fn update(&mut self, finalized_block: Option<BlockNumber>) -> Option<BlockNumber> { fn update(&mut self, finalized_block: Option<BlockNumber>) -> Option<BlockNumber> {
let finalized = finalized_block?; let finalized = finalized_block?;
if self.last_finalized_block.replace(finalized).map_or(true, |last| last < finalized) { self.last_finalized_block
Some(finalized) .replace(finalized)
} else { .map_or(true, |last| last < finalized)
None .then_some(finalized)
}
} }
} }

View File

@ -51,16 +51,14 @@ impl Compact for StoredSubNode {
buf.advance(key_len); buf.advance(key_len);
let nibbles_exists = buf.get_u8() != 0; 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_exists = buf.get_u8() != 0;
let node = if node_exists { let node = node_exists.then(|| {
let (node, rest) = BranchNodeCompact::from_compact(buf, 0); let (node, rest) = BranchNodeCompact::from_compact(buf, 0);
buf = rest; buf = rest;
Some(node) node
} else { });
None
};
(Self { key, nibble, node }, buf) (Self { key, nibble, node }, buf)
} }

View File

@ -49,7 +49,7 @@ impl From<StoredSubNode> for CursorSubNode {
impl From<CursorSubNode> for StoredSubNode { impl From<CursorSubNode> for StoredSubNode {
fn from(value: CursorSubNode) -> Self { 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 } Self { key: value.key.to_vec(), nibble, node: value.node }
} }
} }

View File

@ -111,14 +111,13 @@ where
.accounts .accounts
.get(&hashed_address) .get(&hashed_address)
.ok_or(TrieWitnessError::MissingAccount(hashed_address))?; .ok_or(TrieWitnessError::MissingAccount(hashed_address))?;
let value = if account.is_some() || storage_multiproof.root != EMPTY_ROOT_HASH { let value =
account_rlp.clear(); (account.is_some() || storage_multiproof.root != EMPTY_ROOT_HASH).then(|| {
TrieAccount::from((account.unwrap_or_default(), storage_multiproof.root)) account_rlp.clear();
.encode(&mut account_rlp as &mut dyn BufMut); TrieAccount::from((account.unwrap_or_default(), storage_multiproof.root))
Some(account_rlp.clone()) .encode(&mut account_rlp as &mut dyn BufMut);
} else { account_rlp.clone()
None });
};
let key = Nibbles::unpack(hashed_address); let key = Nibbles::unpack(hashed_address);
account_trie_nodes.extend( account_trie_nodes.extend(
self.target_nodes( self.target_nodes(