Purify Contains, add IsInVec, All and SortedMembers (#8589)

* IsInVec

* Purify `Contains`, introduce SortedMembers
This commit is contained in:
Gavin Wood
2021-04-11 00:04:02 +02:00
committed by GitHub
parent fe775ab954
commit 29864b255c
9 changed files with 60 additions and 15 deletions
+2 -2
View File
@@ -22,7 +22,7 @@ use super::*;
use codec::Encode;
use frame_support::{
assert_noop, assert_ok, parameter_types, ord_parameter_types,
traits::{Contains, OnInitialize, Filter},
traits::{SortedMembers, OnInitialize, Filter},
weights::Weight,
};
use sp_core::H256;
@@ -151,7 +151,7 @@ ord_parameter_types! {
pub const Six: u64 = 6;
}
pub struct OneToFive;
impl Contains<u64> for OneToFive {
impl SortedMembers<u64> for OneToFive {
fn sorted_members() -> Vec<u64> {
vec![1, 2, 3, 4, 5]
}
@@ -107,7 +107,7 @@ use frame_support::{
traits::{
ChangeMembers, Contains, ContainsLengthBound, Currency, CurrencyToVote, Get,
InitializeMembers, LockIdentifier, LockableCurrency, OnUnbalanced, ReservableCurrency,
WithdrawReasons,
WithdrawReasons, SortedMembers,
},
weights::Weight,
};
@@ -1015,6 +1015,12 @@ impl<T: Config> Contains<T::AccountId> for Module<T> {
fn contains(who: &T::AccountId) -> bool {
Self::is_member(who)
}
}
impl<T: Config> SortedMembers<T::AccountId> for Module<T> {
fn contains(who: &T::AccountId) -> bool {
Self::is_member(who)
}
fn sorted_members() -> Vec<T::AccountId> {
Self::members_ids()
+7 -1
View File
@@ -26,7 +26,7 @@
use sp_std::prelude::*;
use frame_support::{
decl_module, decl_storage, decl_event, decl_error,
traits::{ChangeMembers, InitializeMembers, EnsureOrigin, Contains},
traits::{ChangeMembers, InitializeMembers, EnsureOrigin, Contains, SortedMembers},
};
use frame_system::ensure_signed;
@@ -267,6 +267,12 @@ impl<T: Config<I>, I: Instance> Module<T, I> {
}
impl<T: Config<I>, I: Instance> Contains<T::AccountId> for Module<T, I> {
fn contains(t: &T::AccountId) -> bool {
Self::members().binary_search(t).is_ok()
}
}
impl<T: Config<I>, I: Instance> SortedMembers<T::AccountId> for Module<T, I> {
fn sorted_members() -> Vec<T::AccountId> {
Self::members()
}
+4 -1
View File
@@ -459,13 +459,16 @@ macro_rules! ord_parameter_types {
);
() => ();
(IMPL $name:ident , $type:ty , $value:expr) => {
impl $crate::traits::Contains<$type> for $name {
impl $crate::traits::SortedMembers<$type> for $name {
fn contains(t: &$type) -> bool { &$value == t }
fn sorted_members() -> $crate::sp_std::prelude::Vec<$type> { vec![$value] }
fn count() -> usize { 1 }
#[cfg(feature = "runtime-benchmarks")]
fn add(_: &$type) {}
}
impl $crate::traits::Contains<$type> for $name {
fn contains(t: &$type) -> bool { &$value == t }
}
}
}
+4 -1
View File
@@ -29,7 +29,10 @@ pub use tokens::imbalance::{Imbalance, OnUnbalanced, SignedImbalance};
pub use tokens::{ExistenceRequirement, WithdrawReasons, BalanceStatus};
mod members;
pub use members::{Contains, ContainsLengthBound, InitializeMembers, ChangeMembers};
pub use members::{
Contains, ContainsLengthBound, SortedMembers, InitializeMembers, ChangeMembers, All, IsInVec,
AsContains,
};
mod validation;
pub use validation::{
+30 -3
View File
@@ -17,16 +17,28 @@
//! Traits for dealing with the idea of membership.
use sp_std::prelude::*;
use sp_std::{prelude::*, marker::PhantomData};
/// A trait for querying whether a type can be said to "contain" a value.
pub trait Contains<T: Ord> {
pub trait Contains<T> {
/// Return `true` if this "contains" the given value `t`.
fn contains(t: &T) -> bool { Self::sorted_members().binary_search(t).is_ok() }
fn contains(t: &T) -> bool;
}
/// A `Contains` implementation which always returns `true`.
pub struct All<T>(PhantomData<T>);
impl<T: Ord> Contains<T> for All<T> {
fn contains(_: &T) -> bool { true }
}
/// A trait for a set which can enumerate its members in order.
pub trait SortedMembers<T: Ord> {
/// Get a vector of all members in the set, ordered.
fn sorted_members() -> Vec<T>;
/// Return `true` if this "contains" the given value `t`.
fn contains(t: &T) -> bool { Self::sorted_members().binary_search(t).is_ok() }
/// Get the number of items in the set.
fn count() -> usize { Self::sorted_members().len() }
@@ -38,6 +50,21 @@ pub trait Contains<T: Ord> {
fn add(_t: &T) { unimplemented!() }
}
/// Adapter struct for turning an `OrderedMembership` impl into a `Contains` impl.
pub struct AsContains<OM>(PhantomData<(OM,)>);
impl<T: Ord + Eq, OM: SortedMembers<T>> Contains<T> for AsContains<OM> {
fn contains(t: &T) -> bool { OM::contains(t) }
}
/// Trivial utility for implementing `Contains`/`OrderedMembership` with a `Vec`.
pub struct IsInVec<T>(PhantomData<T>);
impl<X: Eq, T: super::Get<Vec<X>>> Contains<X> for IsInVec<T> {
fn contains(t: &X) -> bool { T::get().contains(t) }
}
impl<X: Ord + PartialOrd, T: super::Get<Vec<X>>> SortedMembers<X> for IsInVec<T> {
fn sorted_members() -> Vec<X> { let mut r = T::get(); r.sort(); r }
}
/// A trait for querying bound for the length of an implementation of `Contains`
pub trait ContainsLengthBound {
/// Minimum number of elements contained
+2 -2
View File
@@ -87,7 +87,7 @@ use sp_core::{ChangesTrieConfiguration, storage::well_known_keys};
use frame_support::{
Parameter, storage,
traits::{
Contains, Get, PalletInfo, OnNewAccount, OnKilledAccount, HandleLifetime,
SortedMembers, Get, PalletInfo, OnNewAccount, OnKilledAccount, HandleLifetime,
StoredMap, EnsureOrigin, OriginTrait, Filter,
},
weights::{
@@ -870,7 +870,7 @@ impl<
pub struct EnsureSignedBy<Who, AccountId>(sp_std::marker::PhantomData<(Who, AccountId)>);
impl<
O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
Who: Contains<AccountId>,
Who: SortedMembers<AccountId>,
AccountId: PartialEq + Clone + Ord + Default,
> EnsureOrigin<O> for EnsureSignedBy<Who, AccountId> {
type Success = AccountId;
+2 -2
View File
@@ -68,7 +68,7 @@ use frame_support::traits::{
use sp_runtime::{ Percent, RuntimeDebug, traits::{
Zero, AccountIdConversion, Hash, BadOrigin
}};
use frame_support::traits::{Contains, ContainsLengthBound, OnUnbalanced, EnsureOrigin};
use frame_support::traits::{SortedMembers, ContainsLengthBound, OnUnbalanced, EnsureOrigin};
use codec::{Encode, Decode};
use frame_system::{self as system, ensure_signed};
pub use weights::WeightInfo;
@@ -86,7 +86,7 @@ pub trait Config: frame_system::Config + pallet_treasury::Config {
/// Origin from which tippers must come.
///
/// `ContainsLengthBound::max_len` must be cost free (i.e. no storage read or heavy operation).
type Tippers: Contains<Self::AccountId> + ContainsLengthBound;
type Tippers: SortedMembers<Self::AccountId> + ContainsLengthBound;
/// The period for which a tip remains open after is has achieved threshold tippers.
type TipCountdown: Get<Self::BlockNumber>;
+2 -2
View File
@@ -24,7 +24,7 @@ use super::*;
use std::cell::RefCell;
use frame_support::{
assert_noop, assert_ok, parameter_types,
weights::Weight, traits::Contains,
weights::Weight, traits::SortedMembers,
PalletId
};
use sp_runtime::Permill;
@@ -98,7 +98,7 @@ thread_local! {
static TEN_TO_FOURTEEN: RefCell<Vec<u128>> = RefCell::new(vec![10,11,12,13,14]);
}
pub struct TenToFourteen;
impl Contains<u128> for TenToFourteen {
impl SortedMembers<u128> for TenToFourteen {
fn sorted_members() -> Vec<u128> {
TEN_TO_FOURTEEN.with(|v| {
v.borrow().clone()