mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-13 23:21:06 +00:00
Simplify some Option / Result / ? operator patterns (#8653)
* Simplify some Option / Result / ? operator patterns When those match a combinator exactly. Tool-aided by [comby-rust](https://github.com/huitseeker/comby-rust). * adjust after review * adjust post-review
This commit is contained in:
committed by
GitHub
parent
541692c4a8
commit
052be8bbef
@@ -218,12 +218,9 @@ pub fn for_each_cht_group<Header, I, F, P>(
|
||||
let mut current_cht_num = None;
|
||||
let mut current_cht_blocks = Vec::new();
|
||||
for block in blocks {
|
||||
let new_cht_num = match block_to_cht_number(cht_size, block) {
|
||||
Some(new_cht_num) => new_cht_num,
|
||||
None => return Err(ClientError::Backend(format!(
|
||||
"Cannot compute CHT root for the block #{}", block)).into()
|
||||
),
|
||||
};
|
||||
let new_cht_num = block_to_cht_number(cht_size, block).ok_or_else(|| ClientError::Backend(format!(
|
||||
"Cannot compute CHT root for the block #{}", block))
|
||||
)?;
|
||||
|
||||
let advance_to_next_cht = current_cht_num.is_some() && current_cht_num != Some(new_cht_num);
|
||||
if advance_to_next_cht {
|
||||
|
||||
@@ -226,10 +226,8 @@ impl<Block: BlockT> Blockchain<Block> {
|
||||
|
||||
/// Set an existing block as head.
|
||||
pub fn set_head(&self, id: BlockId<Block>) -> sp_blockchain::Result<()> {
|
||||
let header = match self.header(id)? {
|
||||
Some(h) => h,
|
||||
None => return Err(sp_blockchain::Error::UnknownBlock(format!("{}", id))),
|
||||
};
|
||||
let header = self.header(id)?
|
||||
.ok_or_else(|| sp_blockchain::Error::UnknownBlock(format!("{}", id)))?;
|
||||
|
||||
self.apply_head(&header)
|
||||
}
|
||||
@@ -760,10 +758,8 @@ impl<Block: BlockT> backend::Backend<Block> for Backend<Block> where Block::Hash
|
||||
_ => {},
|
||||
}
|
||||
|
||||
match self.blockchain.id(block).and_then(|id| self.states.read().get(&id).cloned()) {
|
||||
Some(state) => Ok(state),
|
||||
None => Err(sp_blockchain::Error::UnknownBlock(format!("{}", block))),
|
||||
}
|
||||
self.blockchain.id(block).and_then(|id| self.states.read().get(&id).cloned())
|
||||
.ok_or_else(|| sp_blockchain::Error::UnknownBlock(format!("{}", block)))
|
||||
}
|
||||
|
||||
fn revert(
|
||||
|
||||
@@ -51,19 +51,18 @@ impl StorageChangeSet {
|
||||
.map(move |(k,v)| (None, k, v.as_ref()));
|
||||
let children = self.child_changes
|
||||
.iter()
|
||||
.filter_map(move |(sk, changes)| {
|
||||
if let Some(cf) = self.child_filters.as_ref() {
|
||||
if let Some(filter) = cf.get(sk) {
|
||||
Some(changes
|
||||
.filter_map(move |(sk, changes)|
|
||||
self.child_filters.as_ref().and_then(|cf|
|
||||
cf.get(sk).map(|filter| changes
|
||||
.iter()
|
||||
.filter(move |&(key, _)| match filter {
|
||||
Some(ref filter) => filter.contains(key),
|
||||
None => true,
|
||||
})
|
||||
.map(move |(k,v)| (Some(sk), k, v.as_ref())))
|
||||
} else { None }
|
||||
} else { None }
|
||||
})
|
||||
.map(move |(k,v)| (Some(sk), k, v.as_ref()))
|
||||
)
|
||||
)
|
||||
)
|
||||
.flatten();
|
||||
top.chain(children)
|
||||
}
|
||||
|
||||
@@ -72,10 +72,7 @@ fn check_header<C, B: BlockT, P: Pair>(
|
||||
C: sc_client_api::backend::AuxStore,
|
||||
P::Public: Encode + Decode + PartialEq + Clone,
|
||||
{
|
||||
let seal = match header.digest_mut().pop() {
|
||||
Some(x) => x,
|
||||
None => return Err(Error::HeaderUnsealed(hash)),
|
||||
};
|
||||
let seal = header.digest_mut().pop().ok_or_else(|| Error::HeaderUnsealed(hash))?;
|
||||
|
||||
let sig = seal.as_aura_seal().ok_or_else(|| {
|
||||
aura_err(Error::HeaderBadSeal(hash))
|
||||
@@ -89,10 +86,8 @@ fn check_header<C, B: BlockT, P: Pair>(
|
||||
} else {
|
||||
// check the signature is valid under the expected authority and
|
||||
// chain state.
|
||||
let expected_author = match slot_author::<P>(slot, &authorities) {
|
||||
None => return Err(Error::SlotAuthorNotFound),
|
||||
Some(author) => author,
|
||||
};
|
||||
let expected_author = slot_author::<P>(slot, &authorities)
|
||||
.ok_or_else(|| Error::SlotAuthorNotFound)?;
|
||||
|
||||
let pre_hash = header.hash();
|
||||
|
||||
|
||||
@@ -71,10 +71,8 @@ pub(super) fn check_header<B: BlockT + Sized>(
|
||||
let pre_digest = pre_digest.map(Ok).unwrap_or_else(|| find_pre_digest::<B>(&header))?;
|
||||
|
||||
trace!(target: "babe", "Checking header");
|
||||
let seal = match header.digest_mut().pop() {
|
||||
Some(x) => x,
|
||||
None => return Err(babe_err(Error::HeaderUnsealed(header.hash()))),
|
||||
};
|
||||
let seal = header.digest_mut().pop()
|
||||
.ok_or_else(|| babe_err(Error::HeaderUnsealed(header.hash())))?;
|
||||
|
||||
let sig = seal.as_babe_seal().ok_or_else(|| {
|
||||
babe_err(Error::HeaderBadSeal(header.hash()))
|
||||
|
||||
@@ -104,10 +104,7 @@ pub async fn seal_block<B, BI, SC, C, E, P>(
|
||||
// or fetch the best_block.
|
||||
let parent = match parent_hash {
|
||||
Some(hash) => {
|
||||
match client.header(BlockId::Hash(hash))? {
|
||||
Some(header) => header,
|
||||
None => return Err(Error::BlockNotFound(format!("{}", hash))),
|
||||
}
|
||||
client.header(BlockId::Hash(hash))?.ok_or_else(|| Error::BlockNotFound(format!("{}", hash)))?
|
||||
}
|
||||
None => select_chain.best_chain()?
|
||||
};
|
||||
|
||||
@@ -256,10 +256,7 @@ pub trait SimpleSlotWorker<B: BlockT> {
|
||||
return None;
|
||||
}
|
||||
|
||||
let claim = match self.claim_slot(&chain_head, slot, &epoch_data) {
|
||||
None => return None,
|
||||
Some(claim) => claim,
|
||||
};
|
||||
let claim = self.claim_slot(&chain_head, slot, &epoch_data)?;
|
||||
|
||||
if self.should_backoff(slot, &chain_head) {
|
||||
return None;
|
||||
|
||||
@@ -135,10 +135,7 @@ impl<SC: SlotCompatible> Slots<SC> {
|
||||
Err(err) => return Err(sp_consensus::Error::InherentData(err)),
|
||||
};
|
||||
let result = self.timestamp_extractor.extract_timestamp_and_slot(&inherent_data);
|
||||
let (timestamp, slot, offset) = match result {
|
||||
Ok(v) => v,
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
let (timestamp, slot, offset) = result?;
|
||||
// reschedule delay for next slot.
|
||||
let ends_in = offset +
|
||||
time_until_next(timestamp.as_duration(), self.slot_duration);
|
||||
|
||||
@@ -503,10 +503,8 @@ fn read_tries_meta<Block: BlockT>(
|
||||
meta_column: u32,
|
||||
) -> ClientResult<ChangesTriesMeta<Block>> {
|
||||
match db.get(meta_column, meta_keys::CHANGES_TRIES_META) {
|
||||
Some(h) => match Decode::decode(&mut &h[..]) {
|
||||
Ok(h) => Ok(h),
|
||||
Err(err) => Err(ClientError::Backend(format!("Error decoding changes tries metadata: {}", err))),
|
||||
},
|
||||
Some(h) => Decode::decode(&mut &h[..])
|
||||
.map_err(|err| ClientError::Backend(format!("Error decoding changes tries metadata: {}", err))),
|
||||
None => Ok(ChangesTriesMeta {
|
||||
oldest_digest_range: None,
|
||||
oldest_pruned_digest_range_end: Zero::zero(),
|
||||
|
||||
@@ -395,10 +395,8 @@ pub fn read_meta<Block>(db: &dyn Database<DbHash>, col_header: u32) -> Result<
|
||||
};
|
||||
|
||||
let load_meta_block = |desc, key| -> Result<_, sp_blockchain::Error> {
|
||||
if let Some(Some(header)) = match db.get(COLUMN_META, key) {
|
||||
Some(id) => db.get(col_header, &id).map(|b| Block::Header::decode(&mut &b[..]).ok()),
|
||||
None => None,
|
||||
}
|
||||
if let Some(Some(header)) = db.get(COLUMN_META, key)
|
||||
.and_then(|id| db.get(col_header, &id).map(|b| Block::Header::decode(&mut &b[..]).ok()))
|
||||
{
|
||||
let hash = header.hash();
|
||||
debug!(
|
||||
|
||||
@@ -289,14 +289,10 @@ where
|
||||
fn consume(
|
||||
mut self,
|
||||
) -> Option<(AuthoritySet<H, N>, SharedDataLocked<'a, AuthoritySet<H, N>>)> {
|
||||
if let Some(old) = self.old.take() {
|
||||
Some((
|
||||
self.old.take().map(|old| (
|
||||
old,
|
||||
self.guard.take().expect("only taken on deconstruction; qed"),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1134,13 +1134,12 @@ fn local_authority_id(
|
||||
voters: &VoterSet<AuthorityId>,
|
||||
keystore: Option<&SyncCryptoStorePtr>,
|
||||
) -> Option<AuthorityId> {
|
||||
match keystore {
|
||||
Some(keystore) => voters
|
||||
.iter()
|
||||
.find(|(p, _)| {
|
||||
SyncCryptoStore::has_keys(&**keystore, &[(p.to_raw_vec(), AuthorityId::ID)])
|
||||
})
|
||||
.map(|(p, _)| p.clone()),
|
||||
None => None,
|
||||
}
|
||||
keystore.and_then(|keystore| {
|
||||
voters
|
||||
.iter()
|
||||
.find(|(p, _)| {
|
||||
SyncCryptoStore::has_keys(&**keystore, &[(p.to_raw_vec(), AuthorityId::ID)])
|
||||
})
|
||||
.map(|(p, _)| p.clone())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -330,10 +330,7 @@ impl<'a, H, Number, Hash> ChangesTrieRootsStorage<H, Number> for RootsStorage<'a
|
||||
self.prev_roots.get(&Number::unique_saturated_from(block)).cloned()
|
||||
} else {
|
||||
let index: Option<usize> = block.checked_sub(&self.roots.0).and_then(|index| index.checked_into());
|
||||
match index {
|
||||
Some(index) => self.roots.1.get(index as usize).cloned(),
|
||||
None => None,
|
||||
}
|
||||
index.and_then(|index| self.roots.1.get(index as usize).cloned())
|
||||
};
|
||||
|
||||
Ok(root.map(|root| {
|
||||
|
||||
@@ -183,10 +183,7 @@ impl HttpApi {
|
||||
) -> Result<(), HttpError> {
|
||||
// Extract the request from the list.
|
||||
// Don't forget to add it back if necessary when returning.
|
||||
let mut request = match self.requests.remove(&request_id) {
|
||||
None => return Err(HttpError::Invalid),
|
||||
Some(r) => r,
|
||||
};
|
||||
let mut request = self.requests.remove(&request_id).ok_or_else(|| HttpError::Invalid)?;
|
||||
|
||||
let mut deadline = timestamp::deadline_to_future(deadline);
|
||||
// Closure that writes data to a sender, taking the deadline into account. Can return `Ok`
|
||||
|
||||
@@ -272,15 +272,11 @@ impl PeersState {
|
||||
})
|
||||
.map(|(peer_id, _)| peer_id.clone());
|
||||
|
||||
if let Some(peer_id) = outcome {
|
||||
Some(NotConnectedPeer {
|
||||
outcome.map(move |peer_id| NotConnectedPeer {
|
||||
state: self,
|
||||
set,
|
||||
peer_id: Cow::Owned(peer_id),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if there is a free outgoing slot available related to this set.
|
||||
|
||||
@@ -722,13 +722,10 @@ fn maybe_share_remote_request<Block: BlockT, Requests, V, IssueRequest, IssueReq
|
||||
fn display_error<F, T>(future: F) -> impl std::future::Future<Output=Result<T, ()>> where
|
||||
F: std::future::Future<Output=Result<T, Error>>
|
||||
{
|
||||
future.then(|result| ready(match result {
|
||||
Ok(result) => Ok(result),
|
||||
Err(err) => {
|
||||
future.then(|result| ready(result.or_else(|err| {
|
||||
warn!("Remote request for subscription data has failed with: {:?}", err);
|
||||
Err(())
|
||||
},
|
||||
}))
|
||||
})))
|
||||
}
|
||||
|
||||
/// Convert successful future result into Ok(Some(result)) and error into Ok(None),
|
||||
|
||||
@@ -585,10 +585,8 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
|
||||
&dyn PrunableStateChangesTrieStorage<Block>,
|
||||
Vec<(NumberFor<Block>, Option<(NumberFor<Block>, Block::Hash)>, ChangesTrieConfiguration)>,
|
||||
)> {
|
||||
let storage = match self.backend.changes_trie_storage() {
|
||||
Some(storage) => storage,
|
||||
None => return Err(sp_blockchain::Error::ChangesTriesNotSupported),
|
||||
};
|
||||
let storage = self.backend.changes_trie_storage()
|
||||
.ok_or_else(|| sp_blockchain::Error::ChangesTriesNotSupported)?;
|
||||
|
||||
let mut configs = Vec::with_capacity(1);
|
||||
let mut current = last;
|
||||
@@ -1153,10 +1151,8 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
|
||||
/// Gets the uncles of the block with `target_hash` going back `max_generation` ancestors.
|
||||
pub fn uncles(&self, target_hash: Block::Hash, max_generation: NumberFor<Block>) -> sp_blockchain::Result<Vec<Block::Hash>> {
|
||||
let load_header = |id: Block::Hash| -> sp_blockchain::Result<Block::Header> {
|
||||
match self.backend.blockchain().header(BlockId::Hash(id))? {
|
||||
Some(hdr) => Ok(hdr),
|
||||
None => Err(Error::UnknownBlock(format!("{:?}", id))),
|
||||
}
|
||||
self.backend.blockchain().header(BlockId::Hash(id))?
|
||||
.ok_or_else(|| Error::UnknownBlock(format!("{:?}", id)))
|
||||
};
|
||||
|
||||
let genesis_hash = self.backend.blockchain().info().genesis_hash;
|
||||
|
||||
@@ -391,9 +391,8 @@ fn start_rpc_servers<
|
||||
) -> Result<Box<dyn std::any::Any + Send + Sync>, error::Error> {
|
||||
fn maybe_start_server<T, F>(address: Option<SocketAddr>, mut start: F) -> Result<Option<T>, io::Error>
|
||||
where F: FnMut(&SocketAddr) -> Result<T, io::Error>,
|
||||
{
|
||||
Ok(match address {
|
||||
Some(mut address) => Some(start(&address)
|
||||
{
|
||||
address.map(|mut address| start(&address)
|
||||
.or_else(|e| match e.kind() {
|
||||
io::ErrorKind::AddrInUse |
|
||||
io::ErrorKind::PermissionDenied => {
|
||||
@@ -402,10 +401,9 @@ fn start_rpc_servers<
|
||||
start(&address)
|
||||
},
|
||||
_ => Err(e),
|
||||
})?),
|
||||
None => None,
|
||||
})
|
||||
}
|
||||
}
|
||||
) ).transpose()
|
||||
}
|
||||
|
||||
fn deny_unsafe(addr: &SocketAddr, methods: &RpcMethods) -> sc_rpc::DenyUnsafe {
|
||||
let is_exposed_addr = !addr.ip().is_loopback();
|
||||
|
||||
@@ -150,10 +150,8 @@ impl<BlockHash: Hash, Key: Hash> NonCanonicalOverlay<BlockHash, Key> {
|
||||
pub fn new<D: MetaDb>(db: &D) -> Result<NonCanonicalOverlay<BlockHash, Key>, Error<D::Error>> {
|
||||
let last_canonicalized = db.get_meta(&to_meta_key(LAST_CANONICAL, &()))
|
||||
.map_err(|e| Error::Db(e))?;
|
||||
let last_canonicalized = match last_canonicalized {
|
||||
Some(buffer) => Some(<(BlockHash, u64)>::decode(&mut buffer.as_slice())?),
|
||||
None => None,
|
||||
};
|
||||
let last_canonicalized = last_canonicalized
|
||||
.map(|buffer| <(BlockHash, u64)>::decode(&mut buffer.as_slice())).transpose()?;
|
||||
let mut levels = VecDeque::new();
|
||||
let mut parents = HashMap::new();
|
||||
let mut values = HashMap::new();
|
||||
|
||||
@@ -389,10 +389,7 @@ impl Telemetry {
|
||||
/// The `connection_message` argument is a JSON object that is sent every time the connection
|
||||
/// (re-)establishes.
|
||||
pub fn start_telemetry(&mut self, connection_message: ConnectionMessage) -> Result<()> {
|
||||
let endpoints = match self.endpoints.take() {
|
||||
Some(x) => x,
|
||||
None => return Err(Error::TelemetryAlreadyInitialized),
|
||||
};
|
||||
let endpoints = self.endpoints.take().ok_or_else(|| Error::TelemetryAlreadyInitialized)?;
|
||||
|
||||
self.register_sender
|
||||
.unbounded_send(Register::Telemetry {
|
||||
|
||||
@@ -246,7 +246,7 @@ fn parse_target(s: &str) -> (String, Level) {
|
||||
Some(i) => {
|
||||
let target = s[0..i].to_string();
|
||||
if s.len() > i {
|
||||
let level = s[i + 1..s.len()].parse::<Level>().unwrap_or(Level::TRACE);
|
||||
let level = s[i + 1..].parse::<Level>().unwrap_or(Level::TRACE);
|
||||
(target, level)
|
||||
} else {
|
||||
(target, Level::TRACE)
|
||||
|
||||
@@ -322,10 +322,7 @@ impl<B: ChainApi> Pool<B> {
|
||||
) -> Result<(), B::Error> {
|
||||
log::debug!(target: "txpool", "Pruning at {:?}", at);
|
||||
// Prune all transactions that provide given tags
|
||||
let prune_status = match self.validated_pool.prune_tags(tags) {
|
||||
Ok(prune_status) => prune_status,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let prune_status = self.validated_pool.prune_tags(tags)?;
|
||||
|
||||
// Make sure that we don't revalidate extrinsics that were part of the recently
|
||||
// imported block. This is especially important for UTXO-like chains cause the
|
||||
|
||||
@@ -527,12 +527,9 @@ impl<Hash: hash::Hash + Member, Ex> Iterator for BestIterator<Hash, Ex> {
|
||||
satisfied += 1;
|
||||
Some((satisfied, tx_ref))
|
||||
// then get from the pool
|
||||
} else if let Some(next) = self.all.read().get(hash) {
|
||||
Some((next.requires_offset + 1, next.transaction.clone()))
|
||||
} else {
|
||||
None
|
||||
self.all.read().get(hash).map(|next| (next.requires_offset + 1, next.transaction.clone()))
|
||||
};
|
||||
|
||||
if let Some((satisfied, tx_ref)) = res {
|
||||
self.best_or_awaiting(satisfied, tx_ref)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user