Skip to main content

use_predicate/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4//! Small predicate composition helpers.
5
6pub mod prelude;
7
8#[must_use]
9pub fn all<T>(value: &T, predicates: &[fn(&T) -> bool]) -> bool {
10    predicates.iter().all(|predicate| predicate(value))
11}
12
13#[must_use]
14pub fn any<T>(value: &T, predicates: &[fn(&T) -> bool]) -> bool {
15    predicates.iter().any(|predicate| predicate(value))
16}
17
18#[must_use]
19pub fn not<T>(value: &T, predicate: fn(&T) -> bool) -> bool {
20    !predicate(value)
21}
22
23#[must_use]
24pub fn count<T>(value: &T, predicates: &[fn(&T) -> bool]) -> usize {
25    predicates
26        .iter()
27        .filter(|predicate| predicate(value))
28        .count()
29}
30
31#[cfg(test)]
32mod tests {
33    use super::{all, any, count, not};
34
35    #[test]
36    fn predicate_helpers_compose_cleanly() {
37        let predicates: [fn(&i32) -> bool; 2] = [|value| *value > 0, |value| *value % 2 == 0];
38
39        assert!(all(&4, &predicates));
40        assert!(any(&3, &predicates));
41        assert_eq!(count(&4, &predicates), 2);
42        assert!(not(&3, |value| *value < 0));
43    }
44}