mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-14 04:01:10 +00:00
Improve overall performance (#6699)
* Improve overall performance * Clean up code Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Remove needless :: Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> * Remove needless :: Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com> Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
This commit is contained in:
@@ -252,7 +252,7 @@ fn generate_native_call_generators(decl: &ItemTrait) -> Result<TokenStream> {
|
||||
}
|
||||
FnArg::Typed(arg)
|
||||
},
|
||||
r => r.clone(),
|
||||
r => r,
|
||||
});
|
||||
|
||||
let (impl_generics, ty_generics, where_clause) = decl.generics.split_for_impl();
|
||||
|
||||
@@ -417,7 +417,7 @@ fn extend_with_runtime_decl_path(mut trait_: Path) -> Path {
|
||||
};
|
||||
|
||||
let pos = trait_.segments.len() - 1;
|
||||
trait_.segments.insert(pos, runtime.clone().into());
|
||||
trait_.segments.insert(pos, runtime.into());
|
||||
trait_
|
||||
}
|
||||
|
||||
|
||||
@@ -48,8 +48,8 @@ fn main() {
|
||||
digits_u.reverse();
|
||||
digits_v.reverse();
|
||||
|
||||
let num_u = num_bigint::BigUint::new(digits_u.clone());
|
||||
let num_v = num_bigint::BigUint::new(digits_v.clone());
|
||||
let num_u = num_bigint::BigUint::new(digits_u);
|
||||
let num_v = num_bigint::BigUint::new(digits_v);
|
||||
|
||||
if check_digit_lengths(&u, &v, 4) {
|
||||
assert_eq!(u.cmp(&v), ue.cmp(&ve));
|
||||
@@ -146,14 +146,14 @@ fn main() {
|
||||
// Division
|
||||
|
||||
if v.len() == 1 && v.get(0) != 0 {
|
||||
let w = u.clone().div_unit(v.get(0));
|
||||
let num_w = num_u.clone() / &num_v;
|
||||
let w = u.div_unit(v.get(0));
|
||||
let num_w = num_u / &num_v;
|
||||
assert_biguints_eq(&w, &num_w);
|
||||
} else if u.len() > v.len() && v.len() > 0 {
|
||||
let num_remainder = num_u.clone() % num_v.clone();
|
||||
|
||||
let (w, remainder) = u.clone().div(&v, return_remainder).unwrap();
|
||||
let num_w = num_u.clone() / &num_v;
|
||||
let (w, remainder) = u.div(&v, return_remainder).unwrap();
|
||||
let num_w = num_u / &num_v;
|
||||
|
||||
assert_biguints_eq(&w, &num_w);
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ pub trait FixedPointNumber:
|
||||
fn saturating_from_integer<N: FixedPointOperand>(int: N) -> Self {
|
||||
let mut n: I129 = int.into();
|
||||
n.value = n.value.saturating_mul(Self::DIV.saturated_into());
|
||||
Self::from_inner(from_i129(n).unwrap_or(to_bound(int, 0)))
|
||||
Self::from_inner(from_i129(n).unwrap_or_else(|| to_bound(int, 0)))
|
||||
}
|
||||
|
||||
/// Creates `self` from an integer number `int`.
|
||||
@@ -101,7 +101,7 @@ pub trait FixedPointNumber:
|
||||
if d == D::zero() {
|
||||
panic!("attempt to divide by zero")
|
||||
}
|
||||
Self::checked_from_rational(n, d).unwrap_or(to_bound(n, d))
|
||||
Self::checked_from_rational(n, d).unwrap_or_else(|| to_bound(n, d))
|
||||
}
|
||||
|
||||
/// Creates `self` from a rational number. Equal to `n / d`.
|
||||
@@ -137,7 +137,7 @@ pub trait FixedPointNumber:
|
||||
///
|
||||
/// Returns `N::min` or `N::max` if the result does not fit in `N`.
|
||||
fn saturating_mul_int<N: FixedPointOperand>(self, n: N) -> N {
|
||||
self.checked_mul_int(n).unwrap_or(to_bound(self.into_inner(), n))
|
||||
self.checked_mul_int(n).unwrap_or_else(|| to_bound(self.into_inner(), n))
|
||||
}
|
||||
|
||||
/// Checked division for integer type `N`. Equal to `self / d`.
|
||||
@@ -160,7 +160,7 @@ pub trait FixedPointNumber:
|
||||
if d == N::zero() {
|
||||
panic!("attempt to divide by zero")
|
||||
}
|
||||
self.checked_div_int(d).unwrap_or(to_bound(self.into_inner(), d))
|
||||
self.checked_div_int(d).unwrap_or_else(|| to_bound(self.into_inner(), d))
|
||||
}
|
||||
|
||||
/// Saturating multiplication for integer type `N`, adding the result back.
|
||||
@@ -183,7 +183,7 @@ pub trait FixedPointNumber:
|
||||
if inner >= Self::Inner::zero() {
|
||||
self
|
||||
} else {
|
||||
Self::from_inner(inner.checked_neg().unwrap_or(Self::Inner::max_value()))
|
||||
Self::from_inner(inner.checked_neg().unwrap_or_else(|| Self::Inner::max_value()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -301,7 +301,7 @@ impl<N: FixedPointOperand> From<N> for I129 {
|
||||
if n < N::zero() {
|
||||
let value: u128 = n.checked_neg()
|
||||
.map(|n| n.unique_saturated_into())
|
||||
.unwrap_or(N::max_value().unique_saturated_into().saturating_add(1));
|
||||
.unwrap_or_else(|| N::max_value().unique_saturated_into().saturating_add(1));
|
||||
I129 { value, negative: true }
|
||||
} else {
|
||||
I129 { value: n.unique_saturated_into(), negative: false }
|
||||
@@ -399,7 +399,7 @@ macro_rules! implement_fixed {
|
||||
}
|
||||
|
||||
fn saturating_mul(self, rhs: Self) -> Self {
|
||||
self.checked_mul(&rhs).unwrap_or(to_bound(self.0, rhs.0))
|
||||
self.checked_mul(&rhs).unwrap_or_else(|| to_bound(self.0, rhs.0))
|
||||
}
|
||||
|
||||
fn saturating_pow(self, exp: usize) -> Self {
|
||||
|
||||
@@ -108,7 +108,7 @@ impl<B: BlockT, Transaction: Send> ImportQueue<B> for BasicQueue<B, Transaction>
|
||||
) {
|
||||
let _ = self.sender
|
||||
.unbounded_send(
|
||||
ToWorkerMsg::ImportJustification(who.clone(), hash, number, justification)
|
||||
ToWorkerMsg::ImportJustification(who, hash, number, justification)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -180,7 +180,7 @@ impl DeriveJunction {
|
||||
impl<T: AsRef<str>> From<T> for DeriveJunction {
|
||||
fn from(j: T) -> DeriveJunction {
|
||||
let j = j.as_ref();
|
||||
let (code, hard) = if j.starts_with("/") {
|
||||
let (code, hard) = if j.starts_with('/') {
|
||||
(&j[1..], true)
|
||||
} else {
|
||||
(j, false)
|
||||
|
||||
@@ -359,7 +359,7 @@ impl offchain::Externalities for TestOffchainExt {
|
||||
if let Some(req) = state.requests.get_mut(&request_id) {
|
||||
let response = req.response
|
||||
.as_mut()
|
||||
.expect(&format!("No response provided for request: {:?}", request_id));
|
||||
.unwrap_or_else(|| panic!("No response provided for request: {:?}", request_id));
|
||||
|
||||
if req.read >= response.len() {
|
||||
// Remove the pending request as per spec.
|
||||
|
||||
@@ -90,7 +90,7 @@ impl crate::traits::BareCryptoStore for KeyStore {
|
||||
v
|
||||
}))
|
||||
})
|
||||
.unwrap_or(Ok(vec![]))
|
||||
.unwrap_or_else(|| Ok(vec![]))
|
||||
}
|
||||
|
||||
fn sr25519_public_keys(&self, id: KeyTypeId) -> Vec<sr25519::Public> {
|
||||
@@ -222,19 +222,19 @@ impl crate::traits::BareCryptoStore for KeyStore {
|
||||
ed25519::CRYPTO_ID => {
|
||||
let key_pair: ed25519::Pair = self
|
||||
.ed25519_key_pair(id, &ed25519::Public::from_slice(key.1.as_slice()))
|
||||
.ok_or(Error::PairNotFound("ed25519".to_owned()))?;
|
||||
.ok_or_else(|| Error::PairNotFound("ed25519".to_owned()))?;
|
||||
return Ok(key_pair.sign(msg).encode());
|
||||
}
|
||||
sr25519::CRYPTO_ID => {
|
||||
let key_pair: sr25519::Pair = self
|
||||
.sr25519_key_pair(id, &sr25519::Public::from_slice(key.1.as_slice()))
|
||||
.ok_or(Error::PairNotFound("sr25519".to_owned()))?;
|
||||
.ok_or_else(|| Error::PairNotFound("sr25519".to_owned()))?;
|
||||
return Ok(key_pair.sign(msg).encode());
|
||||
}
|
||||
ecdsa::CRYPTO_ID => {
|
||||
let key_pair: ecdsa::Pair = self
|
||||
.ecdsa_key_pair(id, &ecdsa::Public::from_slice(key.1.as_slice()))
|
||||
.ok_or(Error::PairNotFound("ecdsa".to_owned()))?;
|
||||
.ok_or_else(|| Error::PairNotFound("ecdsa".to_owned()))?;
|
||||
return Ok(key_pair.sign(msg).encode());
|
||||
}
|
||||
_ => Err(Error::KeyNotSupported(id))
|
||||
@@ -249,7 +249,7 @@ impl crate::traits::BareCryptoStore for KeyStore {
|
||||
) -> Result<VRFSignature, Error> {
|
||||
let transcript = make_transcript(transcript_data);
|
||||
let pair = self.sr25519_key_pair(key_type, public)
|
||||
.ok_or(Error::PairNotFound("Not found".to_owned()))?;
|
||||
.ok_or_else(|| Error::PairNotFound("Not found".to_owned()))?;
|
||||
|
||||
let (inout, proof, _) = pair.as_ref().vrf_sign(transcript);
|
||||
Ok(VRFSignature {
|
||||
|
||||
@@ -114,7 +114,7 @@ fn main() {
|
||||
*stake_of_tree.get(who).unwrap()
|
||||
};
|
||||
|
||||
let mut staked = assignment_ratio_to_staked(assignments.clone(), &stake_of);
|
||||
let mut staked = assignment_ratio_to_staked(assignments, &stake_of);
|
||||
let winners = to_without_backing(winners);
|
||||
let mut support = build_support_map(winners.as_ref(), staked.as_ref()).0;
|
||||
|
||||
|
||||
@@ -416,7 +416,7 @@ pub fn seq_phragmen<AccountId, R>(
|
||||
n.load.n(),
|
||||
n.budget,
|
||||
c.approval_stake,
|
||||
).unwrap_or(Bounded::max_value());
|
||||
).unwrap_or_else(|_| Bounded::max_value());
|
||||
let temp_d = n.load.d();
|
||||
let temp = Rational128::from(temp_n, temp_d);
|
||||
c.score = c.score.lazy_saturating_add(temp);
|
||||
@@ -470,14 +470,14 @@ pub fn seq_phragmen<AccountId, R>(
|
||||
n.load.n(),
|
||||
)
|
||||
// If result cannot fit in u128. Not much we can do about it.
|
||||
.unwrap_or(Bounded::max_value());
|
||||
.unwrap_or_else(|_| Bounded::max_value());
|
||||
|
||||
TryFrom::try_from(parts)
|
||||
// If the result cannot fit into R::Inner. Defensive only. This can
|
||||
// never happen. `desired_scale * e / n`, where `e / n < 1` always
|
||||
// yields a value smaller than `desired_scale`, which will fit into
|
||||
// R::Inner.
|
||||
.unwrap_or(Bounded::max_value())
|
||||
.unwrap_or_else(|_| Bounded::max_value())
|
||||
} else {
|
||||
// defensive only. Both edge and voter loads are built from
|
||||
// scores, hence MUST have the same denominator.
|
||||
|
||||
@@ -362,11 +362,11 @@ fn reduce_all<A: IdentifierT>(assignments: &mut Vec<StakedAssignment<A>>) -> u32
|
||||
// create both.
|
||||
let voter_node = tree
|
||||
.entry(voter_id.clone())
|
||||
.or_insert(Node::new(voter_id).into_ref())
|
||||
.or_insert_with(|| Node::new(voter_id).into_ref())
|
||||
.clone();
|
||||
let target_node = tree
|
||||
.entry(target_id.clone())
|
||||
.or_insert(Node::new(target_id).into_ref())
|
||||
.or_insert_with(|| Node::new(target_id).into_ref())
|
||||
.clone();
|
||||
|
||||
// If one exists but the other one doesn't, or if both does not, then set the existing
|
||||
|
||||
@@ -46,7 +46,7 @@ pub fn key_changes<'a, H: Hasher, Number: BlockNumber>(
|
||||
key: &'a [u8],
|
||||
) -> Result<DrilldownIterator<'a, H, Number>, String> {
|
||||
// we can't query any roots before root
|
||||
let max = ::std::cmp::min(max.clone(), end.number.clone());
|
||||
let max = std::cmp::min(max, end.number.clone());
|
||||
|
||||
Ok(DrilldownIterator {
|
||||
essence: DrilldownIteratorEssence {
|
||||
@@ -85,7 +85,7 @@ pub fn key_changes_proof<'a, H: Hasher, Number: BlockNumber>(
|
||||
key: &[u8],
|
||||
) -> Result<Vec<Vec<u8>>, String> where H::Out: Codec {
|
||||
// we can't query any roots before root
|
||||
let max = ::std::cmp::min(max.clone(), end.number.clone());
|
||||
let max = std::cmp::min(max, end.number.clone());
|
||||
|
||||
let mut iter = ProvingDrilldownIterator {
|
||||
essence: DrilldownIteratorEssence {
|
||||
@@ -156,7 +156,7 @@ pub fn key_changes_proof_check_with_db<'a, H: Hasher, Number: BlockNumber>(
|
||||
key: &[u8]
|
||||
) -> Result<Vec<(Number, u32)>, String> where H::Out: Encode {
|
||||
// we can't query any roots before root
|
||||
let max = ::std::cmp::min(max.clone(), end.number.clone());
|
||||
let max = std::cmp::min(max, end.number.clone());
|
||||
|
||||
DrilldownIterator {
|
||||
essence: DrilldownIteratorEssence {
|
||||
|
||||
@@ -471,8 +471,8 @@ where
|
||||
let root = self
|
||||
.storage(prefixed_storage_key.as_slice())
|
||||
.and_then(|k| Decode::decode(&mut &k[..]).ok())
|
||||
.unwrap_or(
|
||||
empty_child_trie_root::<Layout<H>>()
|
||||
.unwrap_or_else(
|
||||
|| empty_child_trie_root::<Layout<H>>()
|
||||
);
|
||||
trace!(target: "state", "{:04x}: ChildRoot({})(cached) {}",
|
||||
self.id,
|
||||
@@ -512,8 +512,8 @@ where
|
||||
let root = self
|
||||
.storage(prefixed_storage_key.as_slice())
|
||||
.and_then(|k| Decode::decode(&mut &k[..]).ok())
|
||||
.unwrap_or(
|
||||
empty_child_trie_root::<Layout<H>>()
|
||||
.unwrap_or_else(
|
||||
|| empty_child_trie_root::<Layout<H>>()
|
||||
);
|
||||
trace!(target: "state", "{:04x}: ChildRoot({})(no_change) {}",
|
||||
self.id,
|
||||
|
||||
@@ -109,7 +109,7 @@ where
|
||||
Some(map) => insert_into_memory_db::<H, _>(
|
||||
root,
|
||||
self.backend_storage_mut(),
|
||||
map.clone().into_iter().chain(new_child_roots.into_iter()),
|
||||
map.into_iter().chain(new_child_roots.into_iter()),
|
||||
),
|
||||
None => insert_into_memory_db::<H, _>(
|
||||
root,
|
||||
|
||||
@@ -71,7 +71,7 @@ impl<'a, S, H> ProvingBackendRecorder<'a, S, H>
|
||||
let storage_key = child_info.storage_key();
|
||||
let root = self.storage(storage_key)?
|
||||
.and_then(|r| Decode::decode(&mut &r[..]).ok())
|
||||
.unwrap_or(empty_child_trie_root::<Layout<H>>());
|
||||
.unwrap_or_else(|| empty_child_trie_root::<Layout<H>>());
|
||||
|
||||
let mut read_overlay = S::Overlay::default();
|
||||
let eph = Ephemeral::new(
|
||||
|
||||
@@ -202,7 +202,7 @@ impl<S: TrieBackendStorage<H>, H: Hasher> Backend<H> for TrieBackend<S, H> where
|
||||
let prefixed_storage_key = child_info.prefixed_storage_key();
|
||||
let mut root = match self.storage(prefixed_storage_key.as_slice()) {
|
||||
Ok(value) =>
|
||||
value.and_then(|r| Decode::decode(&mut &r[..]).ok()).unwrap_or(default_root.clone()),
|
||||
value.and_then(|r| Decode::decode(&mut &r[..]).ok()).unwrap_or_else(|| default_root.clone()),
|
||||
Err(e) => {
|
||||
warn!(target: "trie", "Failed to read child storage root: {}", e);
|
||||
default_root.clone()
|
||||
|
||||
@@ -171,7 +171,7 @@ impl<S: TrieBackendStorage<H>, H: Hasher> TrieBackendEssence<S, H> where H::Out:
|
||||
key: &[u8],
|
||||
) -> Result<Option<StorageValue>, String> {
|
||||
let root = self.child_root(child_info)?
|
||||
.unwrap_or(empty_child_trie_root::<Layout<H>>().encode());
|
||||
.unwrap_or_else(|| empty_child_trie_root::<Layout<H>>().encode());
|
||||
|
||||
let map_e = |e| format!("Trie lookup error: {}", e);
|
||||
|
||||
@@ -186,7 +186,7 @@ impl<S: TrieBackendStorage<H>, H: Hasher> TrieBackendEssence<S, H> where H::Out:
|
||||
f: F,
|
||||
) {
|
||||
let root = match self.child_root(child_info) {
|
||||
Ok(v) => v.unwrap_or(empty_child_trie_root::<Layout<H>>().encode()),
|
||||
Ok(v) => v.unwrap_or_else(|| empty_child_trie_root::<Layout<H>>().encode()),
|
||||
Err(e) => {
|
||||
debug!(target: "trie", "Error while iterating child storage: {}", e);
|
||||
return;
|
||||
@@ -211,7 +211,7 @@ impl<S: TrieBackendStorage<H>, H: Hasher> TrieBackendEssence<S, H> where H::Out:
|
||||
mut f: F,
|
||||
) {
|
||||
let root_vec = match self.child_root(child_info) {
|
||||
Ok(v) => v.unwrap_or(empty_child_trie_root::<Layout<H>>().encode()),
|
||||
Ok(v) => v.unwrap_or_else(|| empty_child_trie_root::<Layout<H>>().encode()),
|
||||
Err(e) => {
|
||||
debug!(target: "trie", "Error while iterating child storage: {}", e);
|
||||
return;
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use sp_std::{
|
||||
vec,
|
||||
borrow::Cow, marker::PhantomData, mem, iter::Iterator, result, vec::Vec,
|
||||
};
|
||||
|
||||
@@ -275,8 +276,7 @@ impl PartialEq for dyn Function {
|
||||
pub trait FunctionContext {
|
||||
/// Read memory from `address` into a vector.
|
||||
fn read_memory(&self, address: Pointer<u8>, size: WordSize) -> Result<Vec<u8>> {
|
||||
let mut vec = Vec::with_capacity(size as usize);
|
||||
vec.resize(size as usize, 0);
|
||||
let mut vec = vec![0; size as usize];
|
||||
self.read_memory_into(address, &mut vec)?;
|
||||
Ok(vec)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user