From 59ba8206e2fce4c68b0e37d560883e34c3904d49 Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Tue, 27 Apr 2021 12:00:20 +0200 Subject: [PATCH 1/2] Introduce macro for building Contains impl based on a match --- frame/support/src/traits/members.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/frame/support/src/traits/members.rs b/frame/support/src/traits/members.rs index 35748ca9c0c07..86b7e1f9fcda0 100644 --- a/frame/support/src/traits/members.rs +++ b/frame/support/src/traits/members.rs @@ -31,6 +31,18 @@ impl Contains for All { fn contains(_: &T) -> bool { true } } +#[macro_export] +macro_rules! match_type { + ( pub type $n:ident: impl Contains<$t:ty> = { $phead:pat $( | $ptail:pat )* } ; ) => { + pub struct $n; + impl $crate::traits::Contains<$t> for $n { + fn contains(l: &$t) -> bool { + matches!(l, $phead $( | $ptail )* ) + } + } + } +} + /// A trait for a set which can enumerate its members in order. pub trait SortedMembers { /// Get a vector of all members in the set, ordered. From ce7bcd5baaca83bc34b9b03b402318ee82347b53 Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Tue, 27 Apr 2021 13:30:45 +0200 Subject: [PATCH 2/2] Fixes --- frame/support/src/traits/members.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/frame/support/src/traits/members.rs b/frame/support/src/traits/members.rs index 86b7e1f9fcda0..125f096fa92e1 100644 --- a/frame/support/src/traits/members.rs +++ b/frame/support/src/traits/members.rs @@ -31,6 +31,8 @@ impl Contains for All { fn contains(_: &T) -> bool { true } } +/// Create a type which implements the `Contains` trait for a particular type with syntax similar +/// to `matches!`. #[macro_export] macro_rules! match_type { ( pub type $n:ident: impl Contains<$t:ty> = { $phead:pat $( | $ptail:pat )* } ; ) => { @@ -43,6 +45,22 @@ macro_rules! match_type { } } +#[cfg(test)] +mod tests { + use super::*; + + match_type! { + pub type OneOrTenToTwenty: impl Contains = { 1 | 10..=20 }; + } + + #[test] + fn match_type_works() { + for i in 0..=255 { + assert_eq!(OneOrTenToTwenty::contains(&i), i == 1 || i >= 10 && i <= 20); + } + } +} + /// A trait for a set which can enumerate its members in order. pub trait SortedMembers { /// Get a vector of all members in the set, ordered.