Skip to content

Commit

Permalink
Prefer is_and_then and is_ok_than over map_or (#10408)
Browse files Browse the repository at this point in the history
Option::is_and_then and Result::is_ok_then have been stabilised
in 1.70 and are slightly more concise and arguably more descriptive
than map_or.
  • Loading branch information
mina86 committed Jan 15, 2024
1 parent 4772e05 commit a0386b1
Show file tree
Hide file tree
Showing 17 changed files with 22 additions and 26 deletions.
4 changes: 2 additions & 2 deletions chain/chunks/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ impl ShardsManager {

for part_ord in 0..self.rs.total_shard_count() {
let part_ord = part_ord as u64;
if cache_entry.map_or(false, |cache_entry| cache_entry.parts.contains_key(&part_ord)) {
if cache_entry.is_some_and(|cache_entry| cache_entry.parts.contains_key(&part_ord)) {
continue;
}

Expand Down Expand Up @@ -1757,7 +1757,7 @@ impl ShardsManager {
&& self
.epoch_manager
.get_part_owner(epoch_id, part.part_ord)
.map_or(false, |owner| &owner == me)
.is_ok_and(|owner| &owner == me)
})
.cloned()
.collect();
Expand Down
2 changes: 1 addition & 1 deletion chain/network/src/network_protocol/edge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ impl Edge {

// Checks if edge was created before a given timestamp.
pub fn is_edge_older_than(&self, utc_timestamp: time::Utc) -> bool {
Edge::nonce_to_utc(self.nonce()).map_or(false, |maybe_timestamp| {
Edge::nonce_to_utc(self.nonce()).is_ok_and(|maybe_timestamp| {
// Old-style nonce - for now, assume that they are always fresh.
maybe_timestamp.map_or(false, |nonce_timestamp| nonce_timestamp < utc_timestamp)
})
Expand Down
2 changes: 1 addition & 1 deletion chain/network/src/peer_manager/network_state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ impl NetworkState {
match conn.tier {
tcp::Tier::T1 => {
if conn.peer_type == PeerType::Inbound {
if !this.config.tier1.as_ref().map_or(false, |c| c.enable_inbound) {
if !this.config.tier1.as_ref().is_some_and(|c| c.enable_inbound) {
return Err(RegisterPeerError::Tier1InboundDisabled);
}
// Allow for inbound TIER1 connections only directly from a TIER1 peers.
Expand Down
2 changes: 1 addition & 1 deletion chain/network/src/peer_manager/network_state/routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ impl NetworkState {
}

pub(crate) fn compare_route_back(&self, hash: CryptoHash, peer_id: &PeerId) -> bool {
self.tier2_route_back.lock().get(&hash).map_or(false, |value| value == peer_id)
self.tier2_route_back.lock().get(&hash).is_some_and(|value| value == peer_id)
}

/// Accepts NetworkTopologyChange events.
Expand Down
4 changes: 2 additions & 2 deletions chain/network/src/peer_manager/peer_store/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ impl PeerStore {
}

pub fn is_banned(&self, peer_id: &PeerId) -> bool {
self.0.lock().peer_states.get(peer_id).map_or(false, |s| s.status.is_banned())
self.0.lock().peer_states.get(peer_id).is_some_and(|s| s.status.is_banned())
}

pub fn count_banned(&self) -> usize {
Expand Down Expand Up @@ -488,7 +488,7 @@ impl PeerStore {
for peer_info in peers {
total += 1;
let is_blacklisted =
peer_info.addr.map_or(false, |addr| inner.config.blacklist.contains(addr));
peer_info.addr.is_some_and(|addr| inner.config.blacklist.contains(addr));
if is_blacklisted {
blacklisted += 1;
} else {
Expand Down
7 changes: 2 additions & 5 deletions chain/network/src/peer_manager/peer_store/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,11 +201,8 @@ fn check_exist(
if let Some(peer_info) = inner.peer_states.peek(peer_id) {
let peer_info = &peer_info.peer_info;
if let Some((addr, level)) = addr_level {
peer_info.addr.map_or(false, |cur_addr| cur_addr == addr)
&& inner
.addr_peers
.get(&addr)
.map_or(false, |verified| verified.trust_level == level)
peer_info.addr.is_some_and(|cur_addr| cur_addr == addr)
&& inner.addr_peers.get(&addr).is_some_and(|verified| verified.trust_level == level)
} else {
peer_info.addr.is_none()
}
Expand Down
2 changes: 1 addition & 1 deletion chain/network/src/routing/edge_cache/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ impl EdgeCache {
pub fn has_edge_nonce_or_newer(&self, edge: &Edge) -> bool {
self.verified_nonces
.get(&edge.key().into())
.map_or(false, |cached_nonce| cached_nonce >= &edge.nonce())
.is_some_and(|cached_nonce| cached_nonce >= &edge.nonce())
}

/// Returns the u32 id associated with the given PeerId.
Expand Down
2 changes: 1 addition & 1 deletion chain/network/src/routing/graph/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ struct Inner {
}

fn has(set: &im::HashMap<EdgeKey, Edge>, edge: &Edge) -> bool {
set.get(&edge.key()).map_or(false, |x| x.nonce() >= edge.nonce())
set.get(&edge.key()).is_some_and(|x| x.nonce() >= edge.nonce())
}

impl Inner {
Expand Down
4 changes: 2 additions & 2 deletions integration-tests/src/tests/network/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -530,10 +530,10 @@ pub(crate) fn check_expected_connections(
debug!(target: "test", node_id, expected_connections_lo, ?expected_connections_hi, "runner.rs: check_expected_connections");
let pm = &info.get_node(node_id)?.actix.addr;
let res = pm.send(GetInfo {}.with_span_context()).await?;
if expected_connections_lo.map_or(false, |l| l > res.num_connected_peers) {
if expected_connections_lo.is_some_and(|l| l > res.num_connected_peers) {
return Ok(ControlFlow::Continue(()));
}
if expected_connections_hi.map_or(false, |h| h < res.num_connected_peers) {
if expected_connections_hi.is_some_and(|h| h < res.num_connected_peers) {
return Ok(ControlFlow::Continue(()));
}
Ok(ControlFlow::Break(()))
Expand Down
4 changes: 2 additions & 2 deletions integration-tests/src/tests/runtime/state_viewer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ impl ProofVerifier {
return if &key != nib {
expected.is_none()
} else {
expected.map_or(false, |expected| value == expected)
expected.is_some_and(|expected| value == expected)
};
}
RawTrieNode::Extension(node_key, child_hash) => {
Expand All @@ -85,7 +85,7 @@ impl ProofVerifier {
}
RawTrieNode::BranchWithValue(value, children) => {
if key.is_empty() {
return expected.map_or(false, |exp| value == exp);
return expected.is_some_and(|exp| value == exp);
}
match children[key.at(0)] {
Some(ref child_hash) => {
Expand Down
2 changes: 1 addition & 1 deletion nearcore/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ fn get_split_store(config: &NearConfig, storage: &NodeStorage) -> anyhow::Result
}

// SplitStore should only be used in the view client if it is enabled.
if !config.config.split_storage.as_ref().map_or(false, |c| c.enable_split_storage_view_client) {
if !config.config.split_storage.as_ref().is_some_and(|c| c.enable_split_storage_view_client) {
return Ok(None);
}

Expand Down
3 changes: 1 addition & 2 deletions runtime/near-vm-runner/src/instrument/gas/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,7 @@ fn build_control_flow_graph(
.active_node;

// Increment the charged cost if there are metering instructions to be inserted here.
let apply_block =
metered_blocks_iter.peek().map_or(false, |block| block.start_pos == cursor);
let apply_block = metered_blocks_iter.peek().is_some_and(|block| block.start_pos == cursor);
if apply_block {
let next_metered_block =
metered_blocks_iter.next().expect("peek returned an item; qed");
Expand Down
2 changes: 1 addition & 1 deletion runtime/near-vm-runner/src/prepare/prepare_v0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ impl<'a> ContractModule<'a> {
/// Memory section contains declarations of internal linear memories, so if we find one
/// we reject such a module.
fn ensure_no_internal_memory(self) -> Result<Self, PrepareError> {
if self.module.memory_section().map_or(false, |ms| !ms.entries().is_empty()) {
if self.module.memory_section().is_some_and(|ms| !ms.entries().is_empty()) {
Err(PrepareError::InternalMemoryDeclared)
} else {
Ok(self)
Expand Down
2 changes: 1 addition & 1 deletion runtime/near-vm-runner/src/prepare/prepare_v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ impl<'a> ContractModule<'a> {
/// Memory section contains declarations of internal linear memories, so if we find one
/// we reject such a module.
pub(crate) fn ensure_no_internal_memory(self) -> Result<Self, PrepareError> {
if self.module.memory_section().map_or(false, |ms| !ms.entries().is_empty()) {
if self.module.memory_section().is_some_and(|ms| !ms.entries().is_empty()) {
Err(PrepareError::InternalMemoryDeclared)
} else {
Ok(self)
Expand Down
2 changes: 1 addition & 1 deletion runtime/near-vm/vm/src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ impl Table for LinearTable {
let vec = vec_guard.borrow_mut();
let size = self.size();
let new_len = size.checked_add(delta)?;
if self.maximum.map_or(false, |max| new_len > max) {
if self.maximum.is_some_and(|max| new_len > max) {
return None;
}
if new_len == size {
Expand Down
2 changes: 1 addition & 1 deletion runtime/near-vm/wast/src/wast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ impl Wast {
|| self
.match_trap_messages
.get(expected)
.map_or(false, |alternative| actual.contains(alternative))
.is_some_and(|alternative| actual.contains(alternative))
}

fn val_matches(&self, actual: &Val, expected: &wast::AssertExpression) -> Result<bool> {
Expand Down
2 changes: 1 addition & 1 deletion tools/state-viewer/src/rocksdb_stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ pub fn get_rocksdb_stats(store_dir: &Path, file: Option<PathBuf>) -> anyhow::Res
for entry in std::fs::read_dir(store_dir)? {
let entry = entry?;
let file_name = std::path::PathBuf::from(entry.file_name());
if file_name.extension().map_or(false, |ext| ext == "sst") {
if file_name.extension().is_some_and(|ext| ext == "sst") {
let file_path = store_dir.join(file_name);
eprintln!("Processing ‘{}’...", file_path.display());
data.add_sst_data(SSTFileData::for_sst_file(&file_path)?);
Expand Down

0 comments on commit a0386b1

Please sign in to comment.