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
+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