Skip to main content

refining_str/
chars.rs

1//! Predicates for checking string characters.
2
3use core::{fmt, marker::PhantomData};
4
5use refining_core::predicate::{Predicate, PredicateExpected};
6
7/// Checks whether all [`chars`] of the string satisfy the given predicate.
8///
9/// [`chars`]: str::chars
10pub struct CharsAll<P: Predicate<char> + ?Sized> {
11    predicate: PhantomData<P>,
12}
13
14impl<T: AsRef<str> + ?Sized, P: Predicate<char> + ?Sized> Predicate<T> for CharsAll<P> {
15    fn check(value: &T) -> bool {
16        value.as_ref().chars().all(P::check_value)
17    }
18
19    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
20        write!(
21            formatter,
22            "string with all ({expected})",
23            expected = P::expected()
24        )
25    }
26
27    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
28        write!(
29            formatter,
30            "str::chars::all<{expected:?}>",
31            expected = P::expected()
32        )
33    }
34}
35
36/// Checks whether any [`chars`] of the string satisfy the given predicate.
37///
38/// [`chars`]: str::chars
39pub struct CharsAny<P: Predicate<char> + ?Sized> {
40    predicate: PhantomData<P>,
41}
42
43impl<T: AsRef<str> + ?Sized, P: Predicate<char> + ?Sized> Predicate<T> for CharsAny<P> {
44    fn check(value: &T) -> bool {
45        value.as_ref().chars().any(P::check_value)
46    }
47
48    fn expect(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
49        write!(
50            formatter,
51            "string with any ({expected})",
52            expected = P::expected()
53        )
54    }
55
56    fn expect_code(formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
57        write!(
58            formatter,
59            "str::chars::any<{expected:?}>",
60            expected = P::expected()
61        )
62    }
63}