Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix string to empty string comparison and len zero warnings #5628

Merged
merged 5 commits into from
Jan 3, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion stackslib/src/burnchains/affirmation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,10 @@ impl AffirmationMap {
self.affirmations.len()
}

pub fn is_empty(&self) -> bool {
self.affirmations.is_empty()
}

pub fn as_slice(&self) -> &[AffirmationMapEntry] {
&self.affirmations
}
Expand Down Expand Up @@ -876,7 +880,7 @@ fn inner_find_heaviest_block_commit_ptr(
test_debug!("ancestors = {:?}", &ancestors);
test_debug!("ancestor_confirmations = {:?}", &ancestor_confirmations);

if ancestor_confirmations.len() == 0 {
if ancestor_confirmations.is_empty() {
// empty prepare phase
test_debug!("Prepare-phase has no block-commits");
return None;
Expand Down
2 changes: 1 addition & 1 deletion stackslib/src/burnchains/bitcoin/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ impl SegwitBitcoinAddress {
None
}?;

if quintets.len() == 0 || quintets.len() > 65 {
if quintets.is_empty() || quintets.len() > 65 {
test_debug!("Invalid prog length: {}", quintets.len());
return None;
}
Expand Down
4 changes: 2 additions & 2 deletions stackslib/src/burnchains/bitcoin/bits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ impl BitcoinTxInputStructured {
segwit: bool,
input_txid: (Txid, u32),
) -> Option<BitcoinTxInputStructured> {
if num_sigs < 1 || pubkey_pushbytes.len() < 1 || pubkey_pushbytes.len() < num_sigs {
if num_sigs < 1 || pubkey_pushbytes.is_empty() || pubkey_pushbytes.len() < num_sigs {
test_debug!(
"Not a multisig script: num_sigs = {}, num_pubkeys <= {}",
num_sigs,
Expand Down Expand Up @@ -153,7 +153,7 @@ impl BitcoinTxInputStructured {
pubkey_vecs: &[Vec<u8>],
input_txid: (Txid, u32),
) -> Option<BitcoinTxInputStructured> {
if num_sigs < 1 || pubkey_vecs.len() < 1 || pubkey_vecs.len() < num_sigs {
if num_sigs < 1 || pubkey_vecs.is_empty() || pubkey_vecs.len() < num_sigs {
test_debug!(
"Not a multisig script: num_sigs = {}, num_pubkeys <= {}",
num_sigs,
Expand Down
2 changes: 1 addition & 1 deletion stackslib/src/burnchains/bitcoin/blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ impl BitcoinBlockParser {
tx: &Transaction,
epoch_id: StacksEpochId,
) -> Option<Vec<BitcoinTxOutput>> {
if tx.output.len() == 0 {
if tx.output.is_empty() {
return None;
}

Expand Down
8 changes: 4 additions & 4 deletions stackslib/src/burnchains/bitcoin/indexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -705,7 +705,7 @@ impl BitcoinIndexer {
e
})?;

if reorg_headers.len() == 0 {
if reorg_headers.is_empty() {
// chain shrank considerably
info!(
"Missing Bitcoin headers in block range {}-{} -- did the Bitcoin chain shrink?",
Expand Down Expand Up @@ -736,7 +736,7 @@ impl BitcoinIndexer {
})?;

assert!(
canonical_headers.len() > 0,
!canonical_headers.is_empty(),
"BUG: uninitialized canonical SPV headers DB"
);

Expand Down Expand Up @@ -1379,7 +1379,7 @@ mod test {
spv_client
.insert_block_headers_before(start_block - 1, hdrs)
.unwrap();
} else if hdrs.len() > 0 {
} else if !hdrs.is_empty() {
test_debug!("insert at {}: {:?}", 0, &hdrs);
spv_client.test_write_block_headers(0, hdrs).unwrap();
}
Expand Down Expand Up @@ -1552,7 +1552,7 @@ mod test {
spv_client
.insert_block_headers_before(start_block - 1, hdrs)
.unwrap();
} else if hdrs.len() > 0 {
} else if !hdrs.is_empty() {
test_debug!("insert at {}: {:?}", 0, &hdrs);
spv_client.test_write_block_headers(0, hdrs).unwrap();
}
Expand Down
2 changes: 1 addition & 1 deletion stackslib/src/burnchains/bitcoin/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ impl BitcoinIndexer {

/// Send a GetData message
pub fn send_getdata(&mut self, block_hashes: &Vec<Sha256dHash>) -> Result<(), btc_error> {
assert!(block_hashes.len() > 0);
assert!(!block_hashes.is_empty());
let getdata_invs = block_hashes
.iter()
.map(|h| btc_message_blockdata::Inventory {
Expand Down
8 changes: 4 additions & 4 deletions stackslib/src/burnchains/bitcoin/spv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ impl SpvClient {
headers: &Vec<LoneBlockHeader>,
check_txcount: bool,
) -> Result<(), btc_error> {
if headers.len() == 0 {
if headers.is_empty() {
return Ok(());
}

Expand Down Expand Up @@ -945,7 +945,7 @@ impl SpvClient {
) -> Result<(), btc_error> {
assert!(self.readwrite, "SPV header DB is open read-only");

if block_headers.len() == 0 {
if block_headers.is_empty() {
// no-op
return Ok(());
}
Expand Down Expand Up @@ -996,7 +996,7 @@ impl SpvClient {
block_headers: Vec<LoneBlockHeader>,
) -> Result<(), btc_error> {
assert!(self.readwrite, "SPV header DB is open read-only");
if block_headers.len() == 0 {
if block_headers.is_empty() {
// no-op
return Ok(());
}
Expand Down Expand Up @@ -1137,7 +1137,7 @@ impl SpvClient {
]);
let max_target_bits = BlockHeader::compact_target_from_u256(&max_target);

let parent_header = if headers_in_range.len() > 0 {
let parent_header = if !headers_in_range.is_empty() {
headers_in_range[0]
} else {
match self.read_block_header(current_header_height - 1)? {
Expand Down
2 changes: 1 addition & 1 deletion stackslib/src/burnchains/burnchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ impl BurnchainStateTransition {

block_total_burns.sort();

if block_total_burns.len() == 0 {
if block_total_burns.is_empty() {
return Some(0);
} else if block_total_burns.len() == 1 {
return Some(block_total_burns[0]);
Expand Down
2 changes: 1 addition & 1 deletion stackslib/src/burnchains/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ impl<'a> BurnchainDBTransaction<'a> {
})
.collect()
};
if commits.len() == 0 {
if commits.is_empty() {
test_debug!("No block-commits for block {}", hdr.block_height);
return Ok(());
}
Expand Down
2 changes: 1 addition & 1 deletion stackslib/src/burnchains/tests/burnchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,7 @@ fn test_process_block_ops() {
acc
});

let next_sortition = block_ops_124.len() > 0 && burn_total > 0;
let next_sortition = !block_ops_124.is_empty() && burn_total > 0;

let mut block_124_snapshot = BlockSnapshot {
accumulated_coinbase_ustx: 400_000_000,
Expand Down
6 changes: 3 additions & 3 deletions stackslib/src/burnchains/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ impl TestMiner {
}

pub fn next_VRF_key(&mut self) -> VRFPrivateKey {
let pk = if self.vrf_keys.len() == 0 {
let pk = if self.vrf_keys.is_empty() {
// first key is simply the 32-byte hash of the secret state
let mut buf: Vec<u8> = vec![];
for i in 0..self.privks.len() {
Expand All @@ -204,7 +204,7 @@ impl TestMiner {
}

pub fn next_microblock_privkey(&mut self) -> StacksPrivateKey {
let pk = if self.microblock_privks.len() == 0 {
let pk = if self.microblock_privks.is_empty() {
// first key is simply the 32-byte hash of the secret state
let mut buf: Vec<u8> = vec![];
for i in 0..self.privks.len() {
Expand Down Expand Up @@ -858,7 +858,7 @@ fn process_next_sortition(
let mut next_commits = vec![];
let mut next_prev_keys = vec![];

if prev_keys.len() > 0 {
if !prev_keys.is_empty() {
assert_eq!(miners.len(), prev_keys.len());

// make a Stacks block (hash) for each of the prior block's keys
Expand Down
34 changes: 17 additions & 17 deletions stackslib/src/chainstate/burn/db/sortdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1604,7 +1604,7 @@ impl<'a> SortitionHandleTx<'a> {
anchor_block,
reward_set.rewarded_addresses.len()
);
if reward_set.rewarded_addresses.len() == 0 {
if reward_set.rewarded_addresses.is_empty() {
return Ok(None);
}

Expand Down Expand Up @@ -3587,7 +3587,7 @@ impl SortitionDB {
NO_PARAMS,
)?;

assert!(ast_rule_sets.len() > 0);
assert!(!ast_rule_sets.is_empty());
let mut last_height = ast_rule_sets[0].1;
let mut last_rules = ast_rule_sets[0].0;
for (ast_rules, ast_rule_height) in ast_rule_sets.into_iter() {
Expand Down Expand Up @@ -4049,7 +4049,7 @@ impl SortitionDB {

fn parse_last_anchor_block_hash(s: Option<String>) -> Option<BlockHeaderHash> {
s.map(|s| {
if s == "" {
if s.is_empty() {
None
} else {
Some(BlockHeaderHash::from_hex(&s).expect("BUG: Bad BlockHeaderHash stored in DB"))
Expand All @@ -4060,7 +4060,7 @@ impl SortitionDB {

fn parse_last_anchor_block_txid(s: Option<String>) -> Option<Txid> {
s.map(|s| {
if s == "" {
if s.is_empty() {
None
} else {
Some(Txid::from_hex(&s).expect("BUG: Bad Txid stored in DB"))
Expand Down Expand Up @@ -4593,10 +4593,10 @@ impl SortitionDB {

// remove the first entry -- it's always `n` based on the way we construct it, while the
// heaviest affirmation map just has nothing.
if am.len() > 0 {
Ok(AffirmationMap::new(am.as_slice()[1..].to_vec()))
} else {
if am.is_empty() {
Ok(AffirmationMap::empty())
} else {
Ok(AffirmationMap::new(am.as_slice()[1..].to_vec()))
}
}

Expand Down Expand Up @@ -5239,7 +5239,7 @@ impl SortitionDB {
cache: &mut BlockHeaderCache,
header_data: &Vec<(ConsensusHash, Option<BlockHeaderHash>)>,
) -> () {
if header_data.len() > 0 {
if !header_data.is_empty() {
let mut i = header_data.len() - 1;
while i > 0 {
let cur_consensus_hash = &header_data[i].0;
Expand Down Expand Up @@ -5881,7 +5881,7 @@ impl<'a> SortitionHandleTx<'a> {
"SELECT 1 FROM snapshots WHERE burn_header_hash = ?1 AND pox_valid = 1 LIMIT 1",
&[&snapshot.burn_header_hash],
)?;
if all_valid_sortitions.len() > 0 {
if !all_valid_sortitions.is_empty() {
error!("FATAL: Tried to insert snapshot {:?}, but already have pox-valid sortition for {:?}", &snapshot, &snapshot.burn_header_hash);
panic!();
}
Expand Down Expand Up @@ -6118,7 +6118,10 @@ impl<'a> SortitionHandleTx<'a> {
if let Some(mut reward_set) = reward_info.known_selected_anchor_block_owned() {
// record payouts separately from the remaining addresses, since some of them
// could have just been consumed.
if reward_set.rewarded_addresses.len() > 0 {
if reward_set.rewarded_addresses.is_empty() {
// no payouts
pox_payout_addrs = vec![];
} else {
// if we have a reward set, then we must also have produced a recipient
// info for this block
let mut recipients_to_remove: Vec<_> = recipient_info
Expand All @@ -6136,9 +6139,6 @@ impl<'a> SortitionHandleTx<'a> {
"BUG: Attempted to remove used address from reward set, but failed to do so safely");
}
pox_payout_addrs = addrs;
} else {
// no payouts
pox_payout_addrs = vec![];
}

keys.push(db_keys::pox_reward_set_size().to_string());
Expand Down Expand Up @@ -6321,7 +6321,7 @@ impl<'a> SortitionHandleTx<'a> {
}
}

if tied.len() == 0 {
if tied.is_empty() {
return None;
}
if tied.len() == 1 {
Expand Down Expand Up @@ -10635,10 +10635,10 @@ pub mod tests {
.map(|op| BlockstackOperationType::LeaderBlockCommit(op.clone()))
})
.collect();
let winner = if commit_set.len() > 0 {
commit_set[0].clone()
} else {
let winner = if commit_set.is_empty() {
None
} else {
commit_set[0].clone()
};
let burn_header_hash = headers[i + 1].block_hash.clone();
let burn_block_height = headers[i + 1].block_height;
Expand Down
2 changes: 1 addition & 1 deletion stackslib/src/chainstate/burn/distribution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ impl BurnSamplePoint {
/// Calculate the ranges between 0 and 2**256 - 1 over which each point in the burn sample
/// applies, so we can later select which block to use.
fn make_sortition_ranges(burn_sample: &mut Vec<BurnSamplePoint>) -> () {
if burn_sample.len() == 0 {
if burn_sample.is_empty() {
// empty sample
return;
}
Expand Down
2 changes: 1 addition & 1 deletion stackslib/src/chainstate/burn/operations/delegate_stx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ impl DelegateStxOp {
return Err(op_error::InvalidInput);
}

if outputs.len() == 0 {
if outputs.is_empty() {
warn!(
"Invalid tx: inputs: {}, outputs: {}",
tx.num_signers(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ impl LeaderBlockCommitOp {
return Err(op_error::InvalidInput);
}

if outputs.len() == 0 {
if outputs.is_empty() {
warn!(
"Invalid tx: inputs: {}, outputs: {}",
tx.num_signers(),
Expand Down Expand Up @@ -832,7 +832,7 @@ impl LeaderBlockCommitOp {
/// Check the epoch marker in a block-commit to make sure it matches the right epoch.
/// Valid in Stacks 2.05+
fn check_epoch_commit_marker(&self, marker: u8) -> Result<(), op_error> {
if self.memo.len() < 1 {
if self.memo.is_empty() {
debug!(
"Invalid block commit";
"reason" => "no epoch marker byte given",
Expand Down Expand Up @@ -860,7 +860,7 @@ impl LeaderBlockCommitOp {
}
StacksEpochId::Epoch20 => {
// no-op, but log for helping node operators watch for old nodes
if self.memo.len() < 1 {
if self.memo.is_empty() {
debug!(
"Soon-to-be-invalid block commit";
"reason" => "no epoch marker byte given",
Expand Down
4 changes: 2 additions & 2 deletions stackslib/src/chainstate/burn/operations/stack_stx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ impl PreStxOp {
};

let outputs = tx.get_recipients();
assert!(outputs.len() > 0);
assert!(!outputs.is_empty());

let output = outputs[0]
.as_ref()
Expand Down Expand Up @@ -317,7 +317,7 @@ impl StackStxOp {
})?;

let outputs = tx.get_recipients();
assert!(outputs.len() > 0);
assert!(!outputs.is_empty());

let first_output = outputs[0].as_ref().ok_or_else(|| {
warn!("Invalid tx: failed to decode first output");
Expand Down
2 changes: 1 addition & 1 deletion stackslib/src/chainstate/burn/operations/transfer_stx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ impl TransferStxOp {
})?;

let outputs = tx.get_recipients();
assert!(outputs.len() > 0);
assert!(!outputs.is_empty());

let output = outputs[0]
.as_ref()
Expand Down
4 changes: 2 additions & 2 deletions stackslib/src/chainstate/burn/sortition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl BlockSnapshot {
VRF_seed: &VRFSeed,
sortition_hash: &SortitionHash,
) -> Option<usize> {
if dist.len() == 0 {
if dist.is_empty() {
// no winners
return None;
}
Expand Down Expand Up @@ -592,7 +592,7 @@ impl BlockSnapshot {
)
};

if state_transition.burn_dist.len() == 0 {
if state_transition.burn_dist.is_empty() {
// no burns happened
debug!(
"No burns happened in block";
Expand Down
Loading
Loading