pub trait Predicate<T> {
// Required method
fn test(&self, value: &T) -> bool;
// Provided methods
fn into_box(self) -> BoxPredicate<T>
where Self: Sized + 'static { ... }
fn into_rc(self) -> RcPredicate<T>
where Self: Sized + 'static { ... }
fn into_arc(self) -> ArcPredicate<T>
where Self: Sized + Send + Sync + 'static { ... }
fn into_fn(self) -> impl Fn(&T) -> bool
where Self: Sized + 'static { ... }
fn to_box(&self) -> BoxPredicate<T>
where Self: Clone + Sized + 'static { ... }
fn to_rc(&self) -> RcPredicate<T>
where Self: Clone + Sized + 'static { ... }
fn to_arc(&self) -> ArcPredicate<T>
where Self: Clone + Sized + Send + Sync + 'static { ... }
fn to_fn(&self) -> impl Fn(&T) -> bool
where Self: Clone + Sized + 'static { ... }
}Expand description
A predicate trait for testing whether a value satisfies a condition.
This trait represents a pure judgment operation - it tests whether a given value meets certain criteria without modifying either the value or the predicate itself (from the user’s perspective). This semantic clarity distinguishes predicates from consumers or transformers.
§Design Rationale
This is a minimal trait that only defines:
- The core
testmethod using&self(immutable borrow) - Type conversion methods (
into_box,into_rc,into_arc) - Closure conversion method (
into_fn)
Logical composition methods (and, or, not) are intentionally
not part of the trait. Instead, they are implemented on concrete
types (BoxPredicate, RcPredicate, ArcPredicate), allowing each
implementation to maintain its specific ownership characteristics:
BoxPredicate: Methods consumeself(single ownership)RcPredicate: Methods borrow&self(shared ownership)ArcPredicate: Methods borrow&self(thread-safe shared ownership)
§Why &self Instead of &mut self?
Predicates use &self because:
- Semantic Clarity: A predicate is a judgment, not a mutation
- Flexibility: Can be used in immutable contexts
- Simplicity: No need for
mutin user code - Explicit Stateful Alternative: Use
StatefulPredicatewhen the predicate closure needs nativeFnMut(&T) -> boolsemantics
§Automatic Implementation for Closures
Any closure matching Fn(&T) -> bool automatically implements this
trait, providing seamless integration with Rust’s closure system.
§Examples
§Basic Usage
use qubit_function::Predicate;
let is_positive = |x: &i32| *x > 0;
assert!(is_positive.test(&5));
assert!(!is_positive.test(&-3));§Type Conversion
use qubit_function::{Predicate, BoxPredicate};
let closure = |x: &i32| *x > 0;
let boxed: BoxPredicate<i32> = closure.into_box();
assert!(boxed.test(&5));§Stateful Predicate Alternative
use qubit_function::{StatefulPredicate, BoxStatefulPredicate};
let mut count = 0;
let mut counting_pred = BoxStatefulPredicate::new(move |x: &i32| {
count += 1;
*x > 0
});
assert!(counting_pred.test(&5));
assert!(!counting_pred.test(&-3));Required Methods§
Provided Methods§
Sourcefn into_box(self) -> BoxPredicate<T>where
Self: Sized + 'static,
fn into_box(self) -> BoxPredicate<T>where
Self: Sized + 'static,
Converts this predicate into a BoxPredicate.
The default implementation wraps the predicate in a closure that
calls the test method. Concrete types may override this with
more efficient implementations.
§Returns
A BoxPredicate wrapping this predicate.
Sourcefn into_rc(self) -> RcPredicate<T>where
Self: Sized + 'static,
fn into_rc(self) -> RcPredicate<T>where
Self: Sized + 'static,
Converts this predicate into an RcPredicate.
The default implementation wraps the predicate in a closure that
calls the test method. Concrete types may override this with
more efficient implementations.
§Returns
An RcPredicate wrapping this predicate.
Sourcefn into_arc(self) -> ArcPredicate<T>
fn into_arc(self) -> ArcPredicate<T>
Converts this predicate into an ArcPredicate.
The default implementation wraps the predicate in a closure that
calls the test method. Concrete types may override this with
more efficient implementations.
§Returns
An ArcPredicate wrapping this predicate.
Sourcefn into_fn(self) -> impl Fn(&T) -> boolwhere
Self: Sized + 'static,
fn into_fn(self) -> impl Fn(&T) -> boolwhere
Self: Sized + 'static,
Converts this predicate into a closure that can be used directly with standard library methods.
This method consumes the predicate and returns a closure with
signature Fn(&T) -> bool. Since Fn is a subtrait of FnMut,
the returned closure can be used in any context that requires
either Fn(&T) -> bool or FnMut(&T) -> bool, making it
compatible with methods like Iterator::filter,
Iterator::filter_map, Vec::retain, and similar standard
library APIs.
The default implementation returns a closure that calls the
test method. Concrete types may override this with more
efficient implementations.
§Returns
A closure implementing Fn(&T) -> bool (also usable as
FnMut(&T) -> bool).
§Examples
§Using with Iterator::filter (requires FnMut)
use qubit_function::{Predicate, BoxPredicate};
let pred = BoxPredicate::new(|x: &i32| *x > 0);
let numbers = vec![-2, -1, 0, 1, 2, 3];
let positives: Vec<_> = numbers.iter()
.copied()
.filter(pred.into_fn())
.collect();
assert_eq!(positives, vec![1, 2, 3]);§Using with Vec::retain (requires FnMut)
use qubit_function::{Predicate, BoxPredicate};
let pred = BoxPredicate::new(|x: &i32| *x % 2 == 0);
let mut numbers = vec![1, 2, 3, 4, 5, 6];
numbers.retain(pred.into_fn());
assert_eq!(numbers, vec![2, 4, 6]);Examples found in repository?
30fn demo_with_iterator_filter() {
31 println!("1. Using Iterator::filter");
32
33 let pred = BoxPredicate::new(|x: &i32| *x > 0);
34 let numbers = vec![-2, -1, 0, 1, 2, 3];
35 let positives: Vec<_> = numbers.iter().copied().filter(pred.into_fn()).collect();
36 println!(" Original data: {:?}", numbers);
37 println!(" Filtered result: {:?}", positives);
38 assert_eq!(positives, vec![1, 2, 3]);
39 println!(" ✓ BoxPredicate::into_fn() can be used in filter\n");
40}
41
42/// Demonstrates usage with Vec::retain (retain requires FnMut)
43fn demo_with_vec_retain() {
44 println!("2. Using Vec::retain");
45
46 // RcPredicate example
47 let pred = RcPredicate::new(|x: &i32| *x % 2 == 0);
48 let mut numbers = vec![1, 2, 3, 4, 5, 6];
49 println!(" Original data: {:?}", numbers);
50 numbers.retain(pred.to_fn());
51 println!(" Retained even numbers: {:?}", numbers);
52 assert_eq!(numbers, vec![2, 4, 6]);
53
54 // Original predicate is still available
55 assert!(pred.test(&10));
56 println!(" ✓ RcPredicate::to_fn() can be used in retain");
57 println!(" ✓ Original predicate is still available\n");
58}
59
60/// Demonstrates usage with generic functions that require FnMut
61fn demo_with_generic_function() {
62 println!("3. Using generic functions (requires FnMut)");
63
64 fn count_matching<F>(items: &[i32], mut predicate: F) -> usize
65 where
66 F: FnMut(&i32) -> bool,
67 {
68 items.iter().filter(|x| predicate(x)).count()
69 }
70
71 let pred = RcPredicate::new(|x: &i32| *x > 10);
72 let count1 = count_matching(&[5, 15, 8, 20], pred.to_fn());
73 println!(" First call: count = {}", count1);
74 assert_eq!(count1, 2);
75
76 // Original predicate can be reused
77 let count2 = count_matching(&[12, 3, 18], pred.to_fn());
78 println!(" Second call: count = {}", count2);
79 assert_eq!(count2, 2);
80
81 println!(" ✓ RcPredicate::to_fn() can be passed to generic functions requiring FnMut");
82 println!(" ✓ Original predicate can be converted and used multiple times\n");
83}
84
85/// Demonstrates thread-safe usage
86fn demo_thread_safe() {
87 println!("4. Thread-safe usage");
88
89 let pred = ArcPredicate::new(|x: &i32| *x > 0);
90 // clone and convert into a 'static closure so it can be moved to another thread
91 let closure = pred.clone().into_fn();
92
93 // Closure can be passed between threads
94 let handle = std::thread::spawn(move || {
95 let numbers = [-2, -1, 0, 1, 2, 3];
96 numbers.iter().copied().filter(closure).count()
97 });
98
99 let count = handle.join().expect("thread should not panic");
100 println!(" Filtered result count in thread: {}", count);
101 assert_eq!(count, 3);
102
103 // Original predicate is still available
104 assert!(pred.test(&5));
105 println!(" ✓ ArcPredicate::to_fn() returns a thread-safe closure");
106 println!(" ✓ Original predicate is still available in main thread\n");
107}More examples
17fn main() {
18 println!("=== BoxPredicate always_true/always_false Demo ===\n");
19
20 // BoxPredicate::always_true
21 let always_true: BoxPredicate<i32> = BoxPredicate::always_true();
22 println!("BoxPredicate::always_true():");
23 println!(" test(&42): {}", always_true.test(&42));
24 println!(" test(&-1): {}", always_true.test(&-1));
25 println!(" test(&0): {}", always_true.test(&0));
26 println!(" name: {:?}", always_true.name());
27
28 // BoxPredicate::always_false
29 let always_false: BoxPredicate<i32> = BoxPredicate::always_false();
30 println!("\nBoxPredicate::always_false():");
31 println!(" test(&42): {}", always_false.test(&42));
32 println!(" test(&-1): {}", always_false.test(&-1));
33 println!(" test(&0): {}", always_false.test(&0));
34 println!(" name: {:?}", always_false.name());
35
36 println!("\n=== RcPredicate always_true/always_false Demo ===\n");
37
38 // RcPredicate::always_true
39 let rc_always_true: RcPredicate<String> = RcPredicate::always_true();
40 println!("RcPredicate::always_true():");
41 println!(" test(&\"hello\"): {}", rc_always_true.test(&"hello".to_string()));
42 println!(" test(&\"world\"): {}", rc_always_true.test(&"world".to_string()));
43 println!(" name: {:?}", rc_always_true.name());
44
45 // RcPredicate::always_false
46 let rc_always_false: RcPredicate<String> = RcPredicate::always_false();
47 println!("\nRcPredicate::always_false():");
48 println!(" test(&\"hello\"): {}", rc_always_false.test(&"hello".to_string()));
49 println!(" test(&\"world\"): {}", rc_always_false.test(&"world".to_string()));
50 println!(" name: {:?}", rc_always_false.name());
51
52 // Can be cloned and reused
53 let rc_clone = rc_always_true.clone();
54 println!("\nAfter cloning, still usable:");
55 println!(
56 " Original: test(&\"test\"): {}",
57 rc_always_true.test(&"test".to_string())
58 );
59 println!(" Clone: test(&\"test\"): {}", rc_clone.test(&"test".to_string()));
60
61 println!("\n=== ArcPredicate always_true/always_false Demo ===\n");
62
63 // ArcPredicate::always_true
64 let arc_always_true: ArcPredicate<i32> = ArcPredicate::always_true();
65 println!("ArcPredicate::always_true():");
66 println!(" test(&100): {}", arc_always_true.test(&100));
67 println!(" test(&-100): {}", arc_always_true.test(&-100));
68 println!(" name: {:?}", arc_always_true.name());
69
70 // ArcPredicate::always_false
71 let arc_always_false: ArcPredicate<i32> = ArcPredicate::always_false();
72 println!("\nArcPredicate::always_false():");
73 println!(" test(&100): {}", arc_always_false.test(&100));
74 println!(" test(&-100): {}", arc_always_false.test(&-100));
75 println!(" name: {:?}", arc_always_false.name());
76
77 println!("\n=== Combining with other predicates ===\n");
78
79 // Combining with always_true (AND)
80 let is_positive = BoxPredicate::new(|x: &i32| *x > 0);
81 let combined_and_true = is_positive.and(BoxPredicate::always_true());
82 println!("is_positive AND always_true:");
83 println!(" test(&5): {} (equivalent to is_positive)", combined_and_true.test(&5));
84 println!(
85 " test(&-3): {} (equivalent to is_positive)",
86 combined_and_true.test(&-3)
87 );
88
89 // Combining with always_false (AND)
90 let is_positive = BoxPredicate::new(|x: &i32| *x > 0);
91 let combined_and_false = is_positive.and(BoxPredicate::always_false());
92 println!("\nis_positive AND always_false:");
93 println!(" test(&5): {} (always false)", combined_and_false.test(&5));
94 println!(" test(&-3): {} (always false)", combined_and_false.test(&-3));
95
96 // Combining with always_true (OR)
97 let is_positive = BoxPredicate::new(|x: &i32| *x > 0);
98 let combined_or_true = is_positive.or(BoxPredicate::always_true());
99 println!("\nis_positive OR always_true:");
100 println!(" test(&5): {} (always true)", combined_or_true.test(&5));
101 println!(" test(&-3): {} (always true)", combined_or_true.test(&-3));
102
103 // Combining with always_false (OR)
104 let is_positive = BoxPredicate::new(|x: &i32| *x > 0);
105 let combined_or_false = is_positive.or(BoxPredicate::always_false());
106 println!("\nis_positive OR always_false:");
107 println!(" test(&5): {} (equivalent to is_positive)", combined_or_false.test(&5));
108 println!(
109 " test(&-3): {} (equivalent to is_positive)",
110 combined_or_false.test(&-3)
111 );
112
113 println!("\n=== Practical scenarios: Default pass/reject filters ===\n");
114
115 // Scenario 1: Default pass-all filter
116 let numbers = vec![1, 2, 3, 4, 5];
117 let pass_all = BoxPredicate::<i32>::always_true();
118 let filtered: Vec<_> = numbers.iter().copied().filter(pass_all.into_fn()).collect();
119 println!("Default pass all elements: {:?} -> {:?}", numbers, filtered);
120
121 // Scenario 2: Default reject-all filter
122 let numbers = vec![1, 2, 3, 4, 5];
123 let reject_all = BoxPredicate::<i32>::always_false();
124 let filtered: Vec<_> = numbers.iter().copied().filter(reject_all.into_fn()).collect();
125 println!("Default reject all elements: {:?} -> {:?}", numbers, filtered);
126
127 // Scenario 3: Configurable filter
128 fn configurable_filter(enable_filter: bool) -> BoxPredicate<i32> {
129 if enable_filter {
130 BoxPredicate::new(|x: &i32| *x > 3)
131 } else {
132 BoxPredicate::always_true()
133 }
134 }
135
136 let numbers = vec![1, 2, 3, 4, 5];
137
138 let filter_enabled = configurable_filter(true);
139 let filtered: Vec<_> = numbers.iter().copied().filter(filter_enabled.into_fn()).collect();
140 println!("\nFilter enabled: {:?} -> {:?}", numbers, filtered);
141
142 let filter_disabled = configurable_filter(false);
143 let filtered: Vec<_> = numbers.iter().copied().filter(filter_disabled.into_fn()).collect();
144 println!("Filter disabled: {:?} -> {:?}", numbers, filtered);
145}Sourcefn to_box(&self) -> BoxPredicate<T>
fn to_box(&self) -> BoxPredicate<T>
Converts a reference to this predicate into a BoxPredicate.
This method clones the predicate and then converts it to a
BoxPredicate. The original predicate remains usable after this call.
§Returns
A BoxPredicate wrapping a clone of this predicate.
Sourcefn to_rc(&self) -> RcPredicate<T>
fn to_rc(&self) -> RcPredicate<T>
Converts a reference to this predicate into an RcPredicate.
This method clones the predicate and then converts it to an
RcPredicate. The original predicate remains usable after this call.
§Returns
An RcPredicate wrapping a clone of this predicate.
Sourcefn to_arc(&self) -> ArcPredicate<T>
fn to_arc(&self) -> ArcPredicate<T>
Converts a reference to this predicate into an ArcPredicate.
This method clones the predicate and then converts it to an
ArcPredicate. The original predicate remains usable after this call.
§Returns
An ArcPredicate wrapping a clone of this predicate.
Sourcefn to_fn(&self) -> impl Fn(&T) -> bool
fn to_fn(&self) -> impl Fn(&T) -> bool
Converts a reference to this predicate into a closure that can be used directly with standard library methods.
This method clones the predicate and then converts it to a closure. The original predicate remains usable after this call.
The returned closure has signature Fn(&T) -> bool. Since Fn is a
subtrait of FnMut, it can be used in any context that requires
either Fn(&T) -> bool or FnMut(&T) -> bool, making it compatible
with methods like Iterator::filter, Iterator::filter_map,
Vec::retain, and similar standard library APIs.
§Returns
A closure implementing Fn(&T) -> bool (also usable as
FnMut(&T) -> bool).
Examples found in repository?
43fn demo_with_vec_retain() {
44 println!("2. Using Vec::retain");
45
46 // RcPredicate example
47 let pred = RcPredicate::new(|x: &i32| *x % 2 == 0);
48 let mut numbers = vec![1, 2, 3, 4, 5, 6];
49 println!(" Original data: {:?}", numbers);
50 numbers.retain(pred.to_fn());
51 println!(" Retained even numbers: {:?}", numbers);
52 assert_eq!(numbers, vec![2, 4, 6]);
53
54 // Original predicate is still available
55 assert!(pred.test(&10));
56 println!(" ✓ RcPredicate::to_fn() can be used in retain");
57 println!(" ✓ Original predicate is still available\n");
58}
59
60/// Demonstrates usage with generic functions that require FnMut
61fn demo_with_generic_function() {
62 println!("3. Using generic functions (requires FnMut)");
63
64 fn count_matching<F>(items: &[i32], mut predicate: F) -> usize
65 where
66 F: FnMut(&i32) -> bool,
67 {
68 items.iter().filter(|x| predicate(x)).count()
69 }
70
71 let pred = RcPredicate::new(|x: &i32| *x > 10);
72 let count1 = count_matching(&[5, 15, 8, 20], pred.to_fn());
73 println!(" First call: count = {}", count1);
74 assert_eq!(count1, 2);
75
76 // Original predicate can be reused
77 let count2 = count_matching(&[12, 3, 18], pred.to_fn());
78 println!(" Second call: count = {}", count2);
79 assert_eq!(count2, 2);
80
81 println!(" ✓ RcPredicate::to_fn() can be passed to generic functions requiring FnMut");
82 println!(" ✓ Original predicate can be converted and used multiple times\n");
83}Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".