Skip to main content

refining_regex/
matches.rs

1//! Predicates based on regular expression matches.
2
3use core::{fmt, marker::PhantomData};
4
5use refining_core::{predicate::Predicate, types::StaticStr};
6
7use crate::types::{StaticRegex, TypeRegex};
8
9/// Checks whether the given string matches the regular expression `R`.
10pub struct Matches<R: TypeRegex + ?Sized> {
11    regex: PhantomData<R>,
12}
13
14/// The `regex::matches` literal.
15pub const MATCHES: &str = "regex::matches";
16
17impl<R: TypeRegex + ?Sized> Matches<R> {
18    /// Returns the compiled [`StaticRegex`].
19    #[must_use]
20    pub fn regex() -> StaticRegex {
21        R::get()
22    }
23
24    /// Returns the regular expression pattern.
25    #[must_use]
26    pub fn pattern() -> StaticStr {
27        Self::regex().as_str()
28    }
29}
30
31impl<T: AsRef<str> + ?Sized, R: TypeRegex + ?Sized> Predicate<T> for Matches<R> {
32    fn check(value: &T) -> bool {
33        Self::regex().is_match(value.as_ref())
34    }
35
36    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
37        write!(
38            formatter,
39            "string matching `{pattern}` pattern",
40            pattern = Self::pattern()
41        )
42    }
43
44    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
45        formatter.write_str(MATCHES)
46    }
47}