Skip to content

Commit 4a1fcd8

Browse files
committed
Add str::contains_all function
1 parent 660f658 commit 4a1fcd8

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed

src/prelude.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ pub mod predicate {
2828
/// This module contains predicates specific to string handling.
2929
pub mod str {
3030
pub use crate::str::is_empty;
31-
pub use crate::str::{contains, ends_with, starts_with};
31+
pub use crate::str::{contains, contains_all, ends_with, starts_with};
3232

3333
#[cfg(feature = "diff")]
3434
pub use crate::str::diff;

src/str/basics.rs

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,3 +288,63 @@ where
288288
pattern: pattern.into(),
289289
}
290290
}
291+
292+
/// Predicate that checks for all patterns.
293+
///
294+
/// This is created by `predicates::str:contains_all`.
295+
#[derive(Debug, Clone, PartialEq, Eq)]
296+
pub struct ContainsAllPredicate {
297+
patterns: Vec<String>,
298+
}
299+
300+
impl Predicate<str> for ContainsAllPredicate {
301+
fn eval(&self, variable: &str) -> bool {
302+
for pattern in &self.patterns {
303+
if !variable.contains(pattern) {
304+
return false;
305+
}
306+
}
307+
308+
true
309+
}
310+
}
311+
312+
impl reflection::PredicateReflection for ContainsAllPredicate {}
313+
314+
impl fmt::Display for ContainsAllPredicate {
315+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316+
let palette = crate::Palette::new(f.alternate());
317+
write!(
318+
f,
319+
"{}.{}({})",
320+
palette.var("var"),
321+
palette.description("contains_all"),
322+
palette.expected(format!("{:?}", &self.patterns)),
323+
)
324+
}
325+
}
326+
327+
/// Creates a new `Predicate` that ensures a str contains `pattern`
328+
///
329+
/// # Examples
330+
///
331+
/// ```
332+
/// use predicates::prelude::*;
333+
///
334+
/// let predicate_fn = predicate::str::contains_all(vec!["One Two Three"]);
335+
/// assert_eq!(true, predicate_fn.eval("One Two Three"));
336+
/// assert_eq!(false, predicate_fn.eval("One Two Four"));
337+
/// assert_eq!(false, predicate_fn.eval("Four Five Six"));
338+
/// ```
339+
pub fn contains_all<P, T>(patterns: P) -> ContainsAllPredicate
340+
where
341+
P: IntoIterator<Item = T>,
342+
T: AsRef<str>,
343+
{
344+
let patterns: Vec<_> = patterns
345+
.into_iter()
346+
.map(|p| p.as_ref().to_string())
347+
.collect();
348+
349+
ContainsAllPredicate { patterns }
350+
}

0 commit comments

Comments
 (0)