Skip to content

Commit b929216

Browse files
committed
feat(str): from_utf8 adapter
`from_utf8` takes a `Predicate<str>` and turns it into a `Predicate<u8>`, failing the `eval` if the string is not UTF-8. I'm considering this to fix #21. The rest can be handled on an as-need basis. Fixes #21
1 parent d6af116 commit b929216

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/boolean.rs

+1
Original file line numberDiff line numberDiff line change
@@ -200,5 +200,6 @@ where
200200
impl<P, Item> PredicateBooleanExt<Item> for P
201201
where
202202
P: Predicate<Item>,
203+
Item: ?Sized,
203204
{
204205
}

src/str/adapters.rs

+52
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
use std::ffi;
2+
use std::str;
3+
14
use Predicate;
25

36
/// Predicate adaper that trims the variable being tested.
@@ -20,6 +23,37 @@ where
2023
}
2124
}
2225

26+
/// Predicate adaper that converts a `str` predicate to byte predicate.
27+
///
28+
/// This is created by `pred.from_utf8()`.
29+
#[derive(Copy, Clone, Debug)]
30+
pub struct Utf8Pedicate<P>
31+
where
32+
P: Predicate<str>,
33+
{
34+
p: P,
35+
}
36+
37+
impl<P> Predicate<ffi::OsStr> for Utf8Pedicate<P>
38+
where
39+
P: Predicate<str>,
40+
{
41+
fn eval(&self, variable: &ffi::OsStr) -> bool {
42+
variable.to_str().map(|s| self.p.eval(s)).unwrap_or(false)
43+
}
44+
}
45+
46+
impl<P> Predicate<[u8]> for Utf8Pedicate<P>
47+
where
48+
P: Predicate<str>,
49+
{
50+
fn eval(&self, variable: &[u8]) -> bool {
51+
str::from_utf8(variable)
52+
.map(|s| self.p.eval(s))
53+
.unwrap_or(false)
54+
}
55+
}
56+
2357
/// `Predicate` extension adapting a `str` Predicate.
2458
pub trait PredicateStrExt
2559
where
@@ -40,6 +74,24 @@ where
4074
fn trim(self) -> TrimPedicate<Self> {
4175
TrimPedicate { p: self }
4276
}
77+
78+
/// Returns a `Utf8Pedicate` that adapts `Self` to a `[u8]` `Predicate`.
79+
///
80+
/// # Examples
81+
///
82+
/// ```
83+
/// use predicates::prelude::*;
84+
/// use std::ffi::OsStr;
85+
///
86+
/// let predicate_fn = predicate::str::is_empty().not().from_utf8();
87+
/// assert_eq!(true, predicate_fn.eval(OsStr::new("Hello")));
88+
/// assert_eq!(false, predicate_fn.eval(OsStr::new("")));
89+
/// let variable: &[u8] = b"";
90+
/// assert_eq!(false, predicate_fn.eval(variable));
91+
/// ```
92+
fn from_utf8(self) -> Utf8Pedicate<Self> {
93+
Utf8Pedicate { p: self }
94+
}
4395
}
4496

4597
impl<P> PredicateStrExt for P

0 commit comments

Comments
 (0)