murf/matcher/
string.rs

1use std::fmt::{Display, Formatter, Result as FmtResult};
2
3use super::Matcher;
4
5/// Create a new [`IsEmpty`] matcher, that matches any kind of string, that is empty.
6pub fn is_empty() -> IsEmpty {
7    IsEmpty
8}
9
10/// Implements a [`Matcher`] that matches any kind of string that is empty.
11#[must_use]
12#[derive(Debug)]
13pub struct IsEmpty;
14
15impl<X> Matcher<X> for IsEmpty
16where
17    X: AsRef<str>,
18{
19    fn matches(&self, value: &X) -> bool {
20        value.as_ref().is_empty()
21    }
22}
23
24impl Display for IsEmpty {
25    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
26        write!(f, "IsEmpty")
27    }
28}
29
30macro_rules! impl_str_matcher {
31    ($type:ident, str::$method:ident, $fmt:tt, $ctor_doc:expr, $type_doc:expr) => {
32        #[doc = $ctor_doc]
33        pub fn $method<P: Into<String>>(pattern: P) -> $type {
34            $type(pattern.into())
35        }
36
37        #[derive(Debug)]
38        #[doc = $type_doc]
39        pub struct $type(String);
40
41        impl<X> Matcher<X> for $type
42        where
43            X: AsRef<str>,
44        {
45            fn matches(&self, value: &X) -> bool {
46                value.as_ref().$method(&self.0)
47            }
48        }
49
50        impl Display for $type {
51            fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
52                write!(f, $fmt, self.0)
53            }
54        }
55    };
56}
57
58impl_str_matcher!(
59    StartsWith,
60    str::starts_with,
61    "StartsWith({})",
62    "Create a new [`StartsWith`] matcher, that matches any kind of string, that starts with the passed `pattern`.",
63    "Implements a [`Matcher'] that matches any kind of string, that starts with the passed pattern."
64);
65impl_str_matcher!(
66    EndsWith,
67    str::ends_with,
68    "EndsWith({})",
69    "Create a new [`EndsWith`] matcher, that matches any kind of string, that ends with the passed `pattern`.",
70    "Implements a [`EndsWith'] that matches any kind of string, that starts with the passed pattern."
71);
72impl_str_matcher!(
73    Contains,
74    str::contains,
75    "Contains({})",
76    "Create a new [`Contains`] matcher, that matches any kind of string, that contains the passed `pattern`.",
77    "Implements a [`Contains'] that matches any kind of string, that starts with the passed pattern."
78);