|
| 1 | +use std::ffi; |
| 2 | +use std::str; |
| 3 | + |
1 | 4 | use Predicate;
|
2 | 5 |
|
3 | 6 | /// Predicate adaper that trims the variable being tested.
|
|
20 | 23 | }
|
21 | 24 | }
|
22 | 25 |
|
| 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 | + |
23 | 57 | /// `Predicate` extension adapting a `str` Predicate.
|
24 | 58 | pub trait PredicateStrExt
|
25 | 59 | where
|
|
40 | 74 | fn trim(self) -> TrimPedicate<Self> {
|
41 | 75 | TrimPedicate { p: self }
|
42 | 76 | }
|
| 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 | + } |
43 | 95 | }
|
44 | 96 |
|
45 | 97 | impl<P> PredicateStrExt for P
|
|
0 commit comments