-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
these macros allow for pattern matching either with a closure or pattern respectively
- Loading branch information
Showing
3 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
use super::ArgMatcher; | ||
use std::fmt; | ||
|
||
pub struct Custom<F> { | ||
message: String, | ||
matcher: F, | ||
} | ||
|
||
impl<Arg, F: Fn(&Arg) -> bool> ArgMatcher<Arg> for Custom<F> { | ||
fn matches(&self, argument: &Arg) -> bool { | ||
let matcher = &self.matcher; | ||
matcher(argument) | ||
} | ||
} | ||
|
||
impl<F> fmt::Display for Custom<F> { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
f.write_str(&self.message) | ||
} | ||
} | ||
|
||
pub fn from_fn<Arg>( | ||
matcher: impl Fn(&Arg) -> bool, | ||
message: impl fmt::Display, | ||
) -> impl ArgMatcher<Arg> { | ||
Custom { | ||
matcher, | ||
message: message.to_string(), | ||
} | ||
} | ||
|
||
#[macro_export] | ||
macro_rules! from_fn { | ||
($matcher:expr) => { | ||
faux::matcher::from_fn($matcher, stringify!($matcher)) | ||
}; | ||
} | ||
|
||
#[macro_export] | ||
macro_rules! pattern { | ||
($ty:ty => $( $pattern:pat )|+ $( if $guard: expr )? $(,)?) => ( | ||
faux::matcher::from_fn( | ||
move |arg: &$ty| matches!(arg, $($pattern)|+ $(if $guard)?), | ||
stringify!($($pattern)|+ $(if $guard)?), | ||
) | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters