Skip to main content

refining_str/
bytes.rs

1//! Predicates for checking string bytes.
2
3use core::{fmt, marker::PhantomData};
4
5use refining_core::predicate::{Predicate, PredicateExpected};
6
7/// Checks whether all [`bytes`] of the string satisfy the given predicate.
8///
9/// [`bytes`]: str::bytes
10pub struct BytesAll<P: Predicate<u8> + ?Sized> {
11    predicate: PhantomData<P>,
12}
13
14impl<T: AsRef<str> + ?Sized, P: Predicate<u8> + ?Sized> Predicate<T> for BytesAll<P> {
15    fn check(value: &T) -> bool {
16        value.as_ref().bytes().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::bytes::all<{expected:?}>",
31            expected = P::expected()
32        )
33    }
34}
35
36/// Checks whether any [`bytes`] of the string satisfy the given predicate.
37///
38/// [`bytes`]: str::bytes
39pub struct BytesAny<P: Predicate<u8> + ?Sized> {
40    predicate: PhantomData<P>,
41}
42
43impl<T: AsRef<str> + ?Sized, P: Predicate<u8> + ?Sized> Predicate<T> for BytesAny<P> {
44    fn check(value: &T) -> bool {
45        value.as_ref().bytes().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::bytes::any<{expected:?}>",
60            expected = P::expected()
61        )
62    }
63}