Make clippy _a little_ more annoying (#10570)

* Clippy: +complexity

* Update client/cli/src/arg_enums.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update bin/node/inspect/src/lib.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update primitives/keystore/src/testing.rs

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>

* Update frame/elections/src/lib.rs

Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>

* Update primitives/npos-elections/fuzzer/src/reduce.rs

Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>

* Incorporating feedback

* No need for Ok

* Additional

* Needed slice

* Wigy's suggestions on less derefs

* fix count

* reverting changes brought in by option_map_unit_fn

* add --all-targets

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
Co-authored-by: Keith Yeung <kungfukeith11@gmail.com>
This commit is contained in:
Squirrel
2022-01-05 14:35:30 +00:00
committed by GitHub
parent 48444ffdc0
commit 3dd32d5255
88 changed files with 190 additions and 249 deletions
@@ -61,17 +61,12 @@ pub mod pallet {
pub(super) type NextKeys<T: Config> =
StorageValue<_, WeakBoundedVec<AuthorityId, T::MaxAuthorities>, ValueQuery>;
#[cfg_attr(feature = "std", derive(Default))]
#[pallet::genesis_config]
pub struct GenesisConfig {
pub keys: Vec<AuthorityId>,
}
#[cfg(feature = "std")]
impl Default for GenesisConfig {
fn default() -> Self {
Self { keys: Default::default() }
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
+4 -4
View File
@@ -479,9 +479,9 @@ mod tests {
where
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
{
for (id, data) in digests {
for (id, mut data) in digests {
if id == TEST_ID {
return u64::decode(&mut &data[..]).ok()
return u64::decode(&mut data).ok()
}
}
@@ -499,9 +499,9 @@ mod tests {
let author =
AuthorGiven::find_author(pre_runtime_digests).ok_or_else(|| "no author")?;
for (id, seal) in seals {
for (id, mut seal) in seals {
if id == TEST_ID {
match u64::decode(&mut &seal[..]) {
match u64::decode(&mut seal) {
Err(_) => return Err("wrong seal"),
Ok(a) => {
if a != author {
+1 -7
View File
@@ -310,19 +310,13 @@ pub mod pallet {
#[pallet::storage]
pub(super) type NextEpochConfig<T> = StorageValue<_, BabeEpochConfiguration>;
#[cfg_attr(feature = "std", derive(Default))]
#[pallet::genesis_config]
pub struct GenesisConfig {
pub authorities: Vec<(AuthorityId, BabeAuthorityWeight)>,
pub epoch_config: Option<BabeEpochConfiguration>,
}
#[cfg(feature = "std")]
impl Default for GenesisConfig {
fn default() -> Self {
GenesisConfig { authorities: Default::default(), epoch_config: Default::default() }
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
+1 -1
View File
@@ -742,7 +742,7 @@ impl<T: Config> Bag<T> {
/// Check if the bag contains a node with `id`.
#[cfg(feature = "std")]
fn contains(&self, id: &T::AccountId) -> bool {
self.iter().find(|n| n.id() == id).is_some()
self.iter().any(|n| n.id() == id)
}
}
+2 -7
View File
@@ -409,12 +409,7 @@ pub mod pallet {
let reducible_balance = Self::reducible_balance(&transactor, keep_alive);
let dest = T::Lookup::lookup(dest)?;
let keep_alive = if keep_alive { KeepAlive } else { AllowDeath };
<Self as Currency<_>>::transfer(
&transactor,
&dest,
reducible_balance,
keep_alive.into(),
)?;
<Self as Currency<_>>::transfer(&transactor, &dest, reducible_balance, keep_alive)?;
Ok(())
}
@@ -619,7 +614,7 @@ pub enum Reasons {
impl From<WithdrawReasons> for Reasons {
fn from(r: WithdrawReasons) -> Reasons {
if r == WithdrawReasons::from(WithdrawReasons::TRANSACTION_PAYMENT) {
if r == WithdrawReasons::TRANSACTION_PAYMENT {
Reasons::Fee
} else if r.contains(WithdrawReasons::TRANSACTION_PAYMENT) {
Reasons::All
@@ -592,8 +592,7 @@ mod tests {
contract: BOB,
amount: Deposit::Charge(<Test as Config>::Currency::minimum_balance() * 2),
terminated: false,
}],
..Default::default()
}]
}
)
});
@@ -663,8 +662,7 @@ mod tests {
amount: Deposit::Charge(2),
terminated: false
}
],
..Default::default()
]
}
)
});
@@ -717,8 +715,7 @@ mod tests {
amount: Deposit::Charge(12),
terminated: false
}
],
..Default::default()
]
}
)
});
@@ -1592,7 +1592,7 @@ define_env!(Env, <E: Ext>,
output_len_ptr: u32
) -> u32 => {
use crate::chain_extension::{ChainExtension, Environment, RetVal};
if <E::T as Config>::ChainExtension::enabled() == false {
if !<E::T as Config>::ChainExtension::enabled() {
Err(Error::<E::T>::NoChainExtension)?;
}
let env = Environment::new(ctx, input_ptr, input_len, output_ptr, output_len_ptr);
@@ -544,7 +544,7 @@ impl<T: Config> Pallet<T> {
// Time to finish. We might have reduced less than expected due to rounding error. Increase
// one last time if we have any room left, the reduce until we are sure we are below limit.
while voters + 1 <= max_voters && weight_with(voters + 1) < max_weight {
while voters < max_voters && weight_with(voters + 1) < max_weight {
voters += 1;
}
while voters.checked_sub(1).is_some() && weight_with(voters) > max_weight {
@@ -836,7 +836,7 @@ impl<T: Config> Pallet<T> {
/// Check if `who` is currently an active runner-up.
fn is_runner_up(who: &T::AccountId) -> bool {
Self::runners_up().iter().position(|r| &r.who == who).is_some()
Self::runners_up().iter().any(|r| &r.who == who)
}
/// Get the members' account ids.
+1 -1
View File
@@ -738,7 +738,7 @@ where
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
Ok(self.validate(who, call, info, len).map(|_| ())?)
self.validate(who, call, info, len).map(|_| ())
}
fn validate(
+1 -7
View File
@@ -327,18 +327,12 @@ pub mod pallet {
#[pallet::getter(fn session_for_set)]
pub(super) type SetIdSession<T: Config> = StorageMap<_, Twox64Concat, SetId, SessionIndex>;
#[cfg_attr(feature = "std", derive(Default))]
#[pallet::genesis_config]
pub struct GenesisConfig {
pub authorities: AuthorityList,
}
#[cfg(feature = "std")]
impl Default for GenesisConfig {
fn default() -> Self {
Self { authorities: Default::default() }
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
+1 -1
View File
@@ -341,7 +341,7 @@ fn should_not_send_a_report_if_already_online() {
UintAuthorityId::set_all_keys(vec![1, 2, 3]);
// we expect error, since the authority is already online.
let mut res = ImOnline::send_heartbeats(4).unwrap();
assert_eq!(res.next().unwrap().unwrap(), ());
res.next().unwrap().unwrap();
assert_eq!(res.next().unwrap().unwrap_err(), OffchainErr::AlreadyOnline(1));
assert_eq!(res.next().unwrap().unwrap_err(), OffchainErr::AlreadyOnline(2));
assert_eq!(res.next(), None);
-1
View File
@@ -153,7 +153,6 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
pallet_scored_pool::GenesisConfig::<Test> {
pool: vec![(5, None), (10, Some(1)), (20, Some(2)), (31, Some(2)), (40, Some(3))],
member_count: 2,
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
+3 -3
View File
@@ -480,11 +480,11 @@ pub mod pallet {
let queued_keys: Vec<_> = initial_validators_1
.iter()
.cloned()
.filter_map(|v| {
Some((
.map(|v| {
(
v.clone(),
Pallet::<T>::load_keys(&v).expect("Validator in session 1 missing keys!"),
))
)
})
.collect();
+4 -4
View File
@@ -1290,7 +1290,7 @@ fn pick_item<'a, R: RngCore, T>(rng: &mut R, items: &'a [T]) -> Option<&'a T> {
}
/// Pick a new PRN, in the range [0, `max`] (inclusive).
fn pick_usize<'a, R: RngCore>(rng: &mut R, max: usize) -> usize {
fn pick_usize<R: RngCore>(rng: &mut R, max: usize) -> usize {
(rng.next_u32() % (max as u32 + 1)) as usize
}
@@ -1316,9 +1316,9 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
// Skip ahead to the suggested position
.skip(pos)
// Keep skipping ahead until the position changes
.skip_while(|(_, x)| x.value <= bids[pos].value)
// Get the element when things changed
.next();
.find(|(_, x)| x.value > bids[pos].value);
// If the element is not at the end of the list, insert the new element
// in the spot.
if let Some((p, _)) = different_bid {
@@ -1351,7 +1351,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// Check a user is a bid.
fn is_bid(bids: &Vec<Bid<T::AccountId, BalanceOf<T, I>>>, who: &T::AccountId) -> bool {
// Bids are ordered by `value`, so we cannot binary search for a user.
bids.iter().find(|bid| bid.who == *who).is_some()
bids.iter().any(|bid| bid.who == *who)
}
/// Check a user is a candidate.
+1 -7
View File
@@ -412,7 +412,7 @@ impl<AccountId> Default for RewardDestination<AccountId> {
}
/// Preference of what happens regarding validation.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, Default)]
pub struct ValidatorPrefs {
/// Reward that validator takes up-front; only the rest is split between themselves and
/// nominators.
@@ -424,12 +424,6 @@ pub struct ValidatorPrefs {
pub blocked: bool,
}
impl Default for ValidatorPrefs {
fn default() -> Self {
ValidatorPrefs { commission: Default::default(), blocked: false }
}
}
/// Just a Balance/BlockNumber tuple to encode when a chunk of funds will be unlocked.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct UnlockChunk<Balance: HasCompact> {
+2 -2
View File
@@ -224,7 +224,7 @@ impl<T: Config> Pallet<T> {
let dest = Self::payee(stash);
match dest {
RewardDestination::Controller => Self::bonded(stash)
.and_then(|controller| Some(T::Currency::deposit_creating(&controller, amount))),
.map(|controller| T::Currency::deposit_creating(&controller, amount)),
RewardDestination::Stash => T::Currency::deposit_into_existing(stash, amount).ok(),
RewardDestination::Staked => Self::bonded(stash)
.and_then(|c| Self::ledger(&c).map(|l| (c, l)))
@@ -1160,7 +1160,7 @@ where
add_db_reads_writes(1, 0);
// Reverse because it's more likely to find reports from recent eras.
match eras.iter().rev().filter(|&&(_, ref sesh)| sesh <= &slash_session).next() {
match eras.iter().rev().find(|&&(_, ref sesh)| sesh <= &slash_session) {
Some(&(ref slash_era, _)) => *slash_era,
// Before bonding period. defensive - should be filtered out.
None => return consumed_weight,
+3 -4
View File
@@ -2262,7 +2262,7 @@ fn slash_in_old_span_does_not_deselect() {
);
// the validator doesn't get chilled again
assert!(<Staking as Store>::Validators::iter().find(|(stash, _)| *stash == 11).is_some());
assert!(<Staking as Store>::Validators::iter().any(|(stash, _)| stash == 11));
// but we are still forcing a new era
assert_eq!(Staking::force_era(), Forcing::ForceNew);
@@ -2279,7 +2279,7 @@ fn slash_in_old_span_does_not_deselect() {
);
// the validator doesn't get chilled again
assert!(<Staking as Store>::Validators::iter().find(|(stash, _)| *stash == 11).is_some());
assert!(<Staking as Store>::Validators::iter().any(|(stash, _)| stash == 11));
// but it's disabled
assert!(is_disabled(10));
@@ -4003,8 +4003,7 @@ mod election_data_provider {
assert!(<Validators<Test>>::iter().map(|(x, _)| x).all(|v| Staking::voters(None)
.unwrap()
.into_iter()
.find(|(w, _, t)| { v == *w && t[0] == *w })
.is_some()))
.any(|(w, _, t)| { v == w && t[0] == w })))
})
}
@@ -704,11 +704,11 @@ impl StorageDef {
})
.unwrap_or(Some(QueryKind::OptionQuery)); // This value must match the default generic.
if query_kind.is_none() && getter.is_some() {
if let (None, Some(getter)) = (query_kind.as_ref(), getter.as_ref()) {
let msg = "Invalid pallet::storage, cannot generate getter because QueryKind is not \
identifiable. QueryKind must be `OptionQuery`, `ValueQuery`, or default one to be \
identifiable.";
return Err(syn::Error::new(getter.unwrap().span(), msg))
return Err(syn::Error::new(getter.span(), msg))
}
Ok(StorageDef {
+1 -1
View File
@@ -1546,7 +1546,7 @@ macro_rules! decl_module {
<Self as $crate::traits::GetStorageVersion>::current_storage_version(),
);
(|| { $( $impl )* })()
{ $( $impl )* }
}
#[cfg(feature = "try-runtime")]
@@ -181,8 +181,8 @@ pub fn storage_iter_with_suffix<T: Decode + Sized>(
prefix.extend_from_slice(&storage_prefix);
prefix.extend_from_slice(suffix);
let previous_key = prefix.clone();
let closure = |raw_key_without_prefix: &[u8], raw_value: &[u8]| {
let value = T::decode(&mut &raw_value[..])?;
let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| {
let value = T::decode(&mut raw_value)?;
Ok((raw_key_without_prefix.to_vec(), value))
};
@@ -213,10 +213,10 @@ pub fn storage_key_iter_with_suffix<
prefix.extend_from_slice(&storage_prefix);
prefix.extend_from_slice(suffix);
let previous_key = prefix.clone();
let closure = |raw_key_without_prefix: &[u8], raw_value: &[u8]| {
let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| {
let mut key_material = H::reverse(raw_key_without_prefix);
let key = K::decode(&mut key_material)?;
let value = T::decode(&mut &raw_value[..])?;
let value = T::decode(&mut raw_value)?;
Ok((key, value))
};
PrefixIterator { prefix, previous_key, drain: false, closure, phantom: Default::default() }
+4 -4
View File
@@ -1018,8 +1018,8 @@ impl<T: Decode + Sized> ChildTriePrefixIterator<(Vec<u8>, T)> {
pub fn with_prefix(child_info: &ChildInfo, prefix: &[u8]) -> Self {
let prefix = prefix.to_vec();
let previous_key = prefix.clone();
let closure = |raw_key_without_prefix: &[u8], raw_value: &[u8]| {
let value = T::decode(&mut &raw_value[..])?;
let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| {
let value = T::decode(&mut raw_value)?;
Ok((raw_key_without_prefix.to_vec(), value))
};
@@ -1045,10 +1045,10 @@ impl<K: Decode + Sized, T: Decode + Sized> ChildTriePrefixIterator<(K, T)> {
) -> Self {
let prefix = prefix.to_vec();
let previous_key = prefix.clone();
let closure = |raw_key_without_prefix: &[u8], raw_value: &[u8]| {
let closure = |raw_key_without_prefix: &[u8], mut raw_value: &[u8]| {
let mut key_material = H::reverse(raw_key_without_prefix);
let key = K::decode(&mut key_material)?;
let value = T::decode(&mut &raw_value[..])?;
let value = T::decode(&mut raw_value)?;
Ok((key, value))
};
@@ -30,15 +30,9 @@ pub mod pallet {
pub trait Config: frame_system::Config {}
#[pallet::genesis_config]
#[cfg_attr(feature = "std", derive(Default))]
pub struct GenesisConfig {}
#[cfg(feature = "std")]
impl Default for GenesisConfig {
fn default() -> Self {
Self {}
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {}
@@ -40,5 +40,5 @@ impl Config for Test {}
#[test]
fn init_genesis_config() {
GenesisConfig::<Test> { t: Default::default() };
GenesisConfig::<Test>::default();
}
@@ -184,7 +184,9 @@ frame_support::construct_runtime!(
#[test]
fn create_genesis_config() {
GenesisConfig {
let config = GenesisConfig {
module: module::GenesisConfig { request_life_time: 0, enable_storage_role: true },
};
assert_eq!(config.module.request_life_time, 0);
assert!(config.module.enable_storage_role);
}
+1 -1
View File
@@ -881,7 +881,7 @@ fn pallet_expand_deposit_event() {
#[test]
fn pallet_new_call_variant() {
Call::Example(pallet::Call::new_call_variant_foo(3, 4));
pallet::Call::<Runtime>::new_call_variant_foo(3, 4);
}
#[test]
@@ -70,6 +70,6 @@ impl<T: Config + Send + Sync> SignedExtension for CheckGenesis<T> {
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
Ok(self.validate(who, call, info, len).map(|_| ())?)
self.validate(who, call, info, len).map(|_| ())
}
}
@@ -93,7 +93,7 @@ impl<T: Config + Send + Sync> SignedExtension for CheckMortality<T> {
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
Ok(self.validate(who, call, info, len).map(|_| ())?)
self.validate(who, call, info, len).map(|_| ())
}
}
@@ -72,7 +72,7 @@ where
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
Ok(self.validate(who, call, info, len).map(|_| ())?)
self.validate(who, call, info, len).map(|_| ())
}
fn validate(
@@ -70,6 +70,6 @@ impl<T: Config + Send + Sync> SignedExtension for CheckSpecVersion<T> {
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
Ok(self.validate(who, call, info, len).map(|_| ())?)
self.validate(who, call, info, len).map(|_| ())
}
}
@@ -69,6 +69,6 @@ impl<T: Config + Send + Sync> SignedExtension for CheckTxVersion<T> {
info: &DispatchInfoOf<Self::Call>,
len: usize,
) -> Result<Self::Pre, TransactionValidityError> {
Ok(self.validate(who, call, info, len).map(|_| ())?)
self.validate(who, call, info, len).map(|_| ())
}
}
+1 -7
View File
@@ -637,19 +637,13 @@ pub mod pallet {
#[pallet::storage]
pub(super) type ExecutionPhase<T: Config> = StorageValue<_, Phase>;
#[cfg_attr(feature = "std", derive(Default))]
#[pallet::genesis_config]
pub struct GenesisConfig {
#[serde(with = "sp_core::bytes")]
pub code: Vec<u8>,
}
#[cfg(feature = "std")]
impl Default for GenesisConfig {
fn default() -> Self {
Self { code: Default::default() }
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
+1 -1
View File
@@ -39,7 +39,7 @@ fn assets() -> Vec<(u64, u32, u32)> {
Some(Some(item))
}
})
.filter_map(|item| item)
.flatten()
{
let details = Class::<Test>::get(class).unwrap();
let instances = Asset::<Test>::iter_prefix(class).count() as u32;
+4 -5
View File
@@ -572,14 +572,13 @@ impl<T: Config> Pallet<T> {
let mut total_locked_now: BalanceOf<T> = Zero::zero();
let filtered_schedules = action
.pick_schedules::<T>(schedules)
.filter_map(|schedule| {
.filter(|schedule| {
let locked_now = schedule.locked_at::<T::BlockNumberToBalance>(now);
if locked_now.is_zero() {
None
} else {
let keep = !locked_now.is_zero();
if keep {
total_locked_now = total_locked_now.saturating_add(locked_now);
Some(schedule)
}
keep
})
.collect::<Vec<_>>();