Introduce macro for building Contains impl based on a match (#8675)

* Introduce macro for building Contains impl based on a match

* Fixes
This commit is contained in:
Gavin Wood
2021-04-27 14:33:59 +02:00
committed by GitHub
parent 536cee37f1
commit d02c0222bc
@@ -31,6 +31,36 @@ impl<T: Ord> Contains<T> for All<T> {
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 )* } ; ) => {
pub struct $n;
impl $crate::traits::Contains<$t> for $n {
fn contains(l: &$t) -> bool {
matches!(l, $phead $( | $ptail )* )
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
match_type! {
pub type OneOrTenToTwenty: impl Contains<u8> = { 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<T: Ord> {
/// Get a vector of all members in the set, ordered.