Skip to main content

BoxPredicate

Struct BoxPredicate 

Source
pub struct BoxPredicate<T> { /* private fields */ }
Expand description

A Box-based predicate with single ownership.

This type is suitable for one-time use scenarios where the predicate does not need to be cloned or shared. Composition methods consume self, reflecting the single-ownership model.

§Examples

use qubit_function::{Predicate, BoxPredicate};

let pred = BoxPredicate::new(|x: &i32| *x > 0);
assert!(pred.test(&5));

// Chaining consumes the predicate
let combined = pred.and(BoxPredicate::new(|x| x % 2 == 0));
assert!(combined.test(&4));

Implementations§

Source§

impl<T> BoxPredicate<T>

Source

pub fn new<F>(f: F) -> Self
where F: Fn(&T) -> bool + 'static,

Creates a new predicate.

Wraps the provided closure in the appropriate smart pointer type for this predicate implementation.

Examples found in repository?
examples/predicates/predicate_fn_mut_demo.rs (line 33)
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}
More examples
Hide additional examples
examples/predicates/predicate_demo.rs (line 86)
82fn box_predicate_examples() {
83    println!("--- 2. BoxPredicate Examples (Single Ownership) ---");
84
85    // Basic BoxPredicate
86    let pred = BoxPredicate::new(|x: &i32| *x > 0);
87    println!("BoxPredicate test 5: {}", pred.test(&5));
88
89    // Named predicate for better debugging
90    let named_pred = BoxPredicate::new_with_name("is_positive_even", |x: &i32| *x > 0 && x % 2 == 0);
91    println!("Predicate name: {:?}", named_pred.name());
92    println!("Test 4: {}", named_pred.test(&4));
93
94    // Method chaining - consumes self
95    let positive = BoxPredicate::new_with_name("positive", |x: &i32| *x > 0);
96    let even = BoxPredicate::new_with_name("even", |x: &i32| x % 2 == 0);
97    let combined = positive.and(even);
98    println!("Combined predicate name: {:?}", combined.name());
99    println!("Test 4: {}", combined.test(&4));
100}
101
102/// RcPredicate examples - single-threaded reuse
103fn rc_predicate_examples() {
104    println!("--- 3. RcPredicate Examples (Single-threaded Reuse) ---");
105
106    let is_positive = RcPredicate::new(|x: &i32| *x > 0);
107    let is_even = RcPredicate::new(|x: &i32| x % 2 == 0);
108
109    // Multiple compositions without consuming the original
110    let positive_and_even = is_positive.and(is_even.clone());
111    let positive_or_even = is_positive.or(is_even.clone());
112
113    println!("Original predicates still available:");
114    println!("  is_positive.test(&5) = {}", is_positive.test(&5));
115    println!("  is_even.test(&4) = {}", is_even.test(&4));
116
117    println!("Combined predicates:");
118    println!("  positive_and_even.test(&4) = {}", positive_and_even.test(&4));
119    println!("  positive_or_even.test(&5) = {}", positive_or_even.test(&5));
120
121    // Cloning
122    let cloned = is_positive.clone();
123    println!("Cloned predicate: {}", cloned.test(&10));
124}
125
126/// ArcPredicate examples - multi-threaded scenarios
127fn arc_predicate_examples() {
128    println!("--- 4. ArcPredicate Examples (Multi-threaded Scenarios) ---");
129
130    let is_positive = ArcPredicate::new(|x: &i32| *x > 0);
131    let is_even = ArcPredicate::new(|x: &i32| x % 2 == 0);
132
133    // Create combined predicate
134    let combined = is_positive.and(is_even);
135
136    // Use in multiple threads
137    let handles: Vec<_> = (0..3)
138        .map(|i| {
139            let pred = combined.clone();
140            std::thread::spawn(move || {
141                let value = i * 2;
142                println!("  Thread {} testing {}: {}", i, value, pred.test(&value));
143            })
144        })
145        .collect();
146
147    for handle in handles {
148        handle.join().expect("thread should not panic");
149    }
150
151    // Original predicates still usable
152    println!("Original predicates still available in main thread:");
153    println!("  is_positive.test(&5) = {}", is_positive.test(&5));
154}
155
156/// Logical composition examples
157fn logical_composition_examples() {
158    println!("--- 5. Logical Composition Examples ---");
159
160    let positive = RcPredicate::new_with_name("positive", |x: &i32| *x > 0);
161    let even = RcPredicate::new_with_name("even", |x: &i32| x % 2 == 0);
162    let less_than_ten = RcPredicate::new_with_name("less_than_ten", |x: &i32| *x < 10);
163
164    // AND composition
165    let positive_and_even = positive.and(even.clone());
166    println!("positive AND even: name={:?}", positive_and_even.name());
167    println!("  Test 4: {}", positive_and_even.test(&4));
168    println!("  Test 5: {}", positive_and_even.test(&5));
169
170    // OR composition
171    let positive_or_even = positive.or(even.clone());
172    println!("positive OR even: name={:?}", positive_or_even.name());
173    println!("  Test -2: {}", positive_or_even.test(&-2));
174    println!("  Test 5: {}", positive_or_even.test(&5));
175
176    // NOT composition
177    let not_positive = !&positive;
178    println!("NOT positive: name={:?}", not_positive.name());
179    println!("  Test 5: {}", not_positive.test(&5));
180    println!("  Test -3: {}", not_positive.test(&-3));
181
182    // NAND composition
183    let nand = positive.nand(even.clone());
184    println!("positive NAND even: name={:?}", nand.name());
185    println!("  Test 3: {}", nand.test(&3)); // true NAND false = true
186    println!("  Test 4: {}", nand.test(&4)); // true NAND true = false
187
188    // XOR composition
189    let xor = positive.xor(even.clone());
190    println!("positive XOR even: name={:?}", xor.name());
191    println!("  Test 3: {}", xor.test(&3)); // true XOR false = true
192    println!("  Test 4: {}", xor.test(&4)); // true XOR true = false
193    println!("  Test -2: {}", xor.test(&-2)); // false XOR true = true
194
195    // NOR composition
196    let nor = positive.nor(even.clone());
197    println!("positive NOR even: name={:?}", nor.name());
198    println!("  Test -3: {}", nor.test(&-3)); // false NOR false = true
199    println!("  Test 3: {}", nor.test(&3)); // true NOR false = false
200    println!("  Test -2: {}", nor.test(&-2)); // false NOR true = false
201    println!("  Test 4: {}", nor.test(&4)); // true NOR true = false
202
203    // Complex composition
204    let complex = positive.and(even.clone()).and(less_than_ten.clone());
205    println!("Complex composition: name={:?}", complex.name());
206    println!("  Test 4: {}", complex.test(&4));
207    println!("  Test 12: {}", complex.test(&12));
208}
209
210/// Interior mutability examples
211fn interior_mutability_examples() {
212    println!("--- 6. Interior Mutability Examples ---");
213
214    // BoxPredicate with counter (RefCell)
215    println!("BoxPredicate with counter:");
216    let count = RefCell::new(0);
217    let pred = BoxPredicate::new(move |x: &i32| {
218        *count.borrow_mut() += 1;
219        *x > 0
220    });
221    println!("  Test 5: {}", pred.test(&5));
222    println!("  Test -3: {}", pred.test(&-3));
223    println!("  Test 10: {}", pred.test(&10));
224    // Note: count is moved into the closure, so we can't access it here
225
226    // RcPredicate with cache (RefCell + HashMap)
227    println!("\nRcPredicate with cache:");
228    let cache: RefCell<HashMap<i32, bool>> = RefCell::new(HashMap::new());
229    let expensive_pred = RcPredicate::new(move |x: &i32| {
230        let mut c = cache.borrow_mut();
231        *c.entry(*x).or_insert_with(|| {
232            println!("    Computing result for {} (expensive operation)", x);
233            *x > 0 && x % 2 == 0
234        })
235    });
236
237    println!("  First test 4:");
238    println!("    Result: {}", expensive_pred.test(&4));
239    println!("  Test 4 again (using cache):");
240    println!("    Result: {}", expensive_pred.test(&4));
241    println!("  Test 3:");
242    println!("    Result: {}", expensive_pred.test(&3));
243
244    // ArcPredicate with thread-safe counter (Mutex)
245    println!("\nArcPredicate with thread-safe counter:");
246    let counter = Arc::new(Mutex::new(0));
247    let pred = ArcPredicate::new({
248        let counter = Arc::clone(&counter);
249        move |x: &i32| {
250            let mut c = counter.lock().expect("mutex should not be poisoned");
251            *c += 1;
252            *x > 0
253        }
254    });
255
256    let pred_clone = pred.clone();
257    let counter_clone = Arc::clone(&counter);
258
259    let handle = std::thread::spawn(move || {
260        pred_clone.test(&5);
261        pred_clone.test(&10);
262    });
263
264    pred.test(&3);
265    handle.join().expect("thread should not panic");
266
267    println!(
268        "  Total call count: {}",
269        counter_clone.lock().expect("mutex should not be poisoned")
270    );
271}
examples/predicates/predicate_set_name_demo.rs (line 39)
29fn demo_box_predicate() {
30    println!("1. BoxPredicate Naming Functionality");
31
32    // Create a predicate with name using new_with_name
33    let pred1 = BoxPredicate::new_with_name("is_positive", |x: &i32| *x > 0);
34    println!("   Created with new_with_name:");
35    println!("     Name: {:?}", pred1.name());
36    println!("     Test 5: {}", pred1.test(&5));
37
38    // Set name for an existing predicate using set_name
39    let mut pred2 = BoxPredicate::new(|x: &i32| x % 2 == 0);
40    println!("\n   Created with new then set_name:");
41    println!("     Initial name: {:?}", pred2.name());
42    pred2.set_name("is_even");
43    println!("     Name after setting: {:?}", pred2.name());
44    println!("     Test 4: {}", pred2.test(&4));
45
46    // Combined predicates automatically generate new names
47    let pred3 = BoxPredicate::new_with_name("positive", |x: &i32| *x > 0);
48    let pred4 = BoxPredicate::new_with_name("even", |x: &i32| x % 2 == 0);
49    let combined = pred3.and(pred4);
50    println!("\n   Combined predicate name:");
51    println!("     Auto-generated name: {:?}", combined.name());
52    println!("     Test 4: {}\n", combined.test(&4));
53}
examples/predicates/always_predicate_demo.rs (line 80)
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}
examples/mutators/mutator_once_conditional_demo.rs (lines 60-63)
21fn main() {
22    println!("=== MutatorOnce Conditional Execution Examples ===\n");
23
24    // 1. Basic conditional execution - when condition is satisfied
25    println!("1. Basic conditional execution - when condition is satisfied");
26    let data = vec![1, 2, 3];
27    let mutator = BoxMutatorOnce::new(move |x: &mut Vec<i32>| {
28        println!("   Extending vector with data: {:?}", data);
29        x.extend(data);
30    });
31    let conditional = mutator.when(|x: &Vec<i32>| {
32        println!("   Checking condition: !x.is_empty()");
33        !x.is_empty()
34    });
35
36    let mut target = vec![0];
37    println!("   Initial: {:?}", target);
38    conditional.apply(&mut target);
39    println!("   Result: {:?}\n", target);
40
41    // 2. Conditional execution - when condition is not satisfied
42    println!("2. Conditional execution - when condition is not satisfied");
43    let data = vec![4, 5, 6];
44    let mutator = BoxMutatorOnce::new(move |x: &mut Vec<i32>| {
45        println!("   This should not be executed");
46        x.extend(data);
47    });
48    let conditional = mutator.when(|x: &Vec<i32>| {
49        println!("   Checking condition: x.len() > 10");
50        x.len() > 10
51    });
52
53    let mut target = vec![0];
54    println!("   Initial: {:?}", target);
55    conditional.apply(&mut target);
56    println!("   Result: {:?} (unchanged)\n", target);
57
58    // 3. Using BoxPredicate
59    println!("3. Using BoxPredicate");
60    let pred = BoxPredicate::new(|x: &Vec<i32>| {
61        println!("   Predicate: checking if vector is not empty");
62        !x.is_empty()
63    });
64    let data = vec![7, 8, 9];
65    let mutator = BoxMutatorOnce::new(move |x: &mut Vec<i32>| {
66        println!("   Adding data: {:?}", data);
67        x.extend(data);
68    });
69    let conditional = mutator.when(pred);
70
71    let mut target = vec![0];
72    println!("   Initial: {:?}", target);
73    conditional.apply(&mut target);
74    println!("   Result: {:?}\n", target);
75
76    // 4. Using composed predicate
77    println!("4. Using composed predicate");
78    let pred = (|x: &Vec<i32>| {
79        println!("   Condition 1: !x.is_empty()");
80        !x.is_empty()
81    })
82    .and(|x: &Vec<i32>| {
83        println!("   Condition 2: x.len() < 10");
84        x.len() < 10
85    });
86    let data = vec![10, 11, 12];
87    let mutator = BoxMutatorOnce::new(move |x: &mut Vec<i32>| {
88        println!("   Adding data: {:?}", data);
89        x.extend(data);
90    });
91    let conditional = mutator.when(pred);
92
93    let mut target = vec![0];
94    println!("   Initial: {:?}", target);
95    conditional.apply(&mut target);
96    println!("   Result: {:?}\n", target);
97
98    // 5. If-then-else with or_else - when branch
99    println!("5. If-then-else with or_else - when branch");
100    let data1 = vec![1, 2, 3];
101    let data2 = vec![99];
102    let mutator = BoxMutatorOnce::new(move |x: &mut Vec<i32>| {
103        println!("   When branch: adding {:?}", data1);
104        x.extend(data1);
105    })
106    .when(|x: &Vec<i32>| {
107        println!("   Checking: !x.is_empty()");
108        !x.is_empty()
109    })
110    .or_else(move |x: &mut Vec<i32>| {
111        println!("   Else branch: adding {:?}", data2);
112        x.extend(data2);
113    });
114
115    let mut target = vec![0];
116    println!("   Initial: {:?}", target);
117    mutator.apply(&mut target);
118    println!("   Result: {:?}\n", target);
119
120    // 6. If-then-else with or_else - else branch
121    println!("6. If-then-else with or_else - else branch");
122    let data1 = vec![4, 5, 6];
123    let data2 = vec![99];
124    let mutator = BoxMutatorOnce::new(move |x: &mut Vec<i32>| {
125        println!("   When branch: adding {:?}", data1);
126        x.extend(data1);
127    })
128    .when(|x: &Vec<i32>| {
129        println!("   Checking: x.is_empty()");
130        x.is_empty()
131    })
132    .or_else(move |x: &mut Vec<i32>| {
133        println!("   Else branch: adding {:?}", data2);
134        x.extend(data2);
135    });
136
137    let mut target = vec![0];
138    println!("   Initial: {:?}", target);
139    mutator.apply(&mut target);
140    println!("   Result: {:?}\n", target);
141
142    // 7. Conditional with integers
143    println!("7. Conditional with integers");
144    let mutator = BoxMutatorOnce::new(|x: &mut i32| {
145        println!("   Multiplying by 2");
146        *x *= 2;
147    })
148    .when(|x: &i32| {
149        println!("   Checking: *x > 0");
150        *x > 0
151    });
152
153    let mut positive = 5;
154    println!("   Initial (positive): {}", positive);
155    mutator.apply(&mut positive);
156    println!("   Result: {}\n", positive);
157
158    // 8. Conditional with integers - not executed
159    println!("8. Conditional with integers - not executed");
160    let mutator = BoxMutatorOnce::new(|x: &mut i32| {
161        println!("   This should not be executed");
162        *x *= 2;
163    })
164    .when(|x: &i32| {
165        println!("   Checking: *x > 0");
166        *x > 0
167    });
168
169    let mut negative = -5;
170    println!("   Initial (negative): {}", negative);
171    mutator.apply(&mut negative);
172    println!("   Result: {} (unchanged)\n", negative);
173
174    // 9. Chaining conditional mutators
175    println!("9. Chaining conditional mutators");
176    let data1 = vec![1, 2];
177    let cond1 = BoxMutatorOnce::new(move |x: &mut Vec<i32>| {
178        println!("   First mutator: adding {:?}", data1);
179        x.extend(data1);
180    })
181    .when(|x: &Vec<i32>| {
182        println!("   First condition: !x.is_empty()");
183        !x.is_empty()
184    });
185
186    let data2 = vec![3, 4];
187    let cond2 = BoxMutatorOnce::new(move |x: &mut Vec<i32>| {
188        println!("   Second mutator: adding {:?}", data2);
189        x.extend(data2);
190    })
191    .when(|x: &Vec<i32>| {
192        println!("   Second condition: x.len() < 10");
193        x.len() < 10
194    });
195
196    let chained = cond1.and_then(cond2);
197
198    let mut target = vec![0];
199    println!("   Initial: {:?}", target);
200    chained.apply(&mut target);
201    println!("   Result: {:?}\n", target);
202
203    // 10. Complex conditional chain
204    println!("10. Complex conditional chain");
205    let data1 = vec![1, 2];
206    let data2 = vec![99];
207    let data3 = vec![5, 6];
208
209    let mutator = BoxMutatorOnce::new(move |x: &mut Vec<i32>| {
210        println!("   When branch: adding {:?}", data1);
211        x.extend(data1);
212    })
213    .when(|x: &Vec<i32>| {
214        println!("   Checking: !x.is_empty()");
215        !x.is_empty()
216    })
217    .or_else(move |x: &mut Vec<i32>| {
218        println!("   Else branch: adding {:?}", data2);
219        x.extend(data2);
220    })
221    .and_then(move |x: &mut Vec<i32>| {
222        println!("   Final step: adding {:?}", data3);
223        x.extend(data3);
224    });
225
226    let mut target = vec![0];
227    println!("   Initial: {:?}", target);
228    mutator.apply(&mut target);
229    println!("   Result: {:?}\n", target);
230
231    // 11. Real-world scenario: data validation and processing
232    println!("11. Real-world scenario: data validation and processing");
233
234    struct DataProcessor {
235        on_valid: Option<BoxMutatorOnce<Vec<String>>>,
236        on_invalid: Option<BoxMutatorOnce<Vec<String>>>,
237    }
238
239    impl DataProcessor {
240        fn new<V, I>(on_valid: V, on_invalid: I) -> Self
241        where
242            V: FnOnce(&mut Vec<String>) + 'static,
243            I: FnOnce(&mut Vec<String>) + 'static,
244        {
245            Self {
246                on_valid: Some(BoxMutatorOnce::new(on_valid)),
247                on_invalid: Some(BoxMutatorOnce::new(on_invalid)),
248            }
249        }
250
251        fn process(mut self, data: &mut Vec<String>) {
252            let is_valid = !data.is_empty() && data.iter().all(|s| !s.is_empty());
253            println!("   Data validation: {}", if is_valid { "VALID" } else { "INVALID" });
254
255            if is_valid {
256                if let Some(callback) = self.on_valid.take() {
257                    callback.apply(data);
258                }
259            } else if let Some(callback) = self.on_invalid.take() {
260                callback.apply(data);
261            }
262        }
263    }
264
265    let valid_suffix = vec!["processed".to_string()];
266    let invalid_marker = vec!["[INVALID]".to_string()];
267
268    let processor = DataProcessor::new(
269        move |data| {
270            println!("   Valid data callback: adding suffix");
271            data.extend(valid_suffix);
272        },
273        move |data| {
274            println!("   Invalid data callback: adding error marker");
275            data.clear();
276            data.extend(invalid_marker);
277        },
278    );
279
280    let mut valid_data = vec!["item1".to_string(), "item2".to_string()];
281    println!("   Processing valid data: {:?}", valid_data);
282    processor.process(&mut valid_data);
283    println!("   Result: {:?}\n", valid_data);
284
285    println!("=== Examples completed ===");
286}
Source

pub fn new_with_name<F>(name: &str, f: F) -> Self
where F: Fn(&T) -> bool + 'static,

Creates a new named predicate.

Wraps the provided closure and assigns it a name, which is useful for debugging and logging purposes.

Examples found in repository?
examples/predicates/predicate_demo.rs (line 90)
82fn box_predicate_examples() {
83    println!("--- 2. BoxPredicate Examples (Single Ownership) ---");
84
85    // Basic BoxPredicate
86    let pred = BoxPredicate::new(|x: &i32| *x > 0);
87    println!("BoxPredicate test 5: {}", pred.test(&5));
88
89    // Named predicate for better debugging
90    let named_pred = BoxPredicate::new_with_name("is_positive_even", |x: &i32| *x > 0 && x % 2 == 0);
91    println!("Predicate name: {:?}", named_pred.name());
92    println!("Test 4: {}", named_pred.test(&4));
93
94    // Method chaining - consumes self
95    let positive = BoxPredicate::new_with_name("positive", |x: &i32| *x > 0);
96    let even = BoxPredicate::new_with_name("even", |x: &i32| x % 2 == 0);
97    let combined = positive.and(even);
98    println!("Combined predicate name: {:?}", combined.name());
99    println!("Test 4: {}", combined.test(&4));
100}
More examples
Hide additional examples
examples/predicates/predicate_set_name_demo.rs (line 33)
29fn demo_box_predicate() {
30    println!("1. BoxPredicate Naming Functionality");
31
32    // Create a predicate with name using new_with_name
33    let pred1 = BoxPredicate::new_with_name("is_positive", |x: &i32| *x > 0);
34    println!("   Created with new_with_name:");
35    println!("     Name: {:?}", pred1.name());
36    println!("     Test 5: {}", pred1.test(&5));
37
38    // Set name for an existing predicate using set_name
39    let mut pred2 = BoxPredicate::new(|x: &i32| x % 2 == 0);
40    println!("\n   Created with new then set_name:");
41    println!("     Initial name: {:?}", pred2.name());
42    pred2.set_name("is_even");
43    println!("     Name after setting: {:?}", pred2.name());
44    println!("     Test 4: {}", pred2.test(&4));
45
46    // Combined predicates automatically generate new names
47    let pred3 = BoxPredicate::new_with_name("positive", |x: &i32| *x > 0);
48    let pred4 = BoxPredicate::new_with_name("even", |x: &i32| x % 2 == 0);
49    let combined = pred3.and(pred4);
50    println!("\n   Combined predicate name:");
51    println!("     Auto-generated name: {:?}", combined.name());
52    println!("     Test 4: {}\n", combined.test(&4));
53}
Source

pub fn new_with_optional_name<F>(f: F, name: Option<String>) -> Self
where F: Fn(&T) -> bool + 'static,

Creates a new named predicate with an optional name.

Wraps the provided closure and assigns it an optional name.

Source

pub fn name(&self) -> Option<&str>

Gets the name of this predicate.

§Returns

Returns Some(&str) if a name was set, None otherwise.

Examples found in repository?
examples/predicates/predicate_demo.rs (line 91)
82fn box_predicate_examples() {
83    println!("--- 2. BoxPredicate Examples (Single Ownership) ---");
84
85    // Basic BoxPredicate
86    let pred = BoxPredicate::new(|x: &i32| *x > 0);
87    println!("BoxPredicate test 5: {}", pred.test(&5));
88
89    // Named predicate for better debugging
90    let named_pred = BoxPredicate::new_with_name("is_positive_even", |x: &i32| *x > 0 && x % 2 == 0);
91    println!("Predicate name: {:?}", named_pred.name());
92    println!("Test 4: {}", named_pred.test(&4));
93
94    // Method chaining - consumes self
95    let positive = BoxPredicate::new_with_name("positive", |x: &i32| *x > 0);
96    let even = BoxPredicate::new_with_name("even", |x: &i32| x % 2 == 0);
97    let combined = positive.and(even);
98    println!("Combined predicate name: {:?}", combined.name());
99    println!("Test 4: {}", combined.test(&4));
100}
More examples
Hide additional examples
examples/predicates/predicate_set_name_demo.rs (line 35)
29fn demo_box_predicate() {
30    println!("1. BoxPredicate Naming Functionality");
31
32    // Create a predicate with name using new_with_name
33    let pred1 = BoxPredicate::new_with_name("is_positive", |x: &i32| *x > 0);
34    println!("   Created with new_with_name:");
35    println!("     Name: {:?}", pred1.name());
36    println!("     Test 5: {}", pred1.test(&5));
37
38    // Set name for an existing predicate using set_name
39    let mut pred2 = BoxPredicate::new(|x: &i32| x % 2 == 0);
40    println!("\n   Created with new then set_name:");
41    println!("     Initial name: {:?}", pred2.name());
42    pred2.set_name("is_even");
43    println!("     Name after setting: {:?}", pred2.name());
44    println!("     Test 4: {}", pred2.test(&4));
45
46    // Combined predicates automatically generate new names
47    let pred3 = BoxPredicate::new_with_name("positive", |x: &i32| *x > 0);
48    let pred4 = BoxPredicate::new_with_name("even", |x: &i32| x % 2 == 0);
49    let combined = pred3.and(pred4);
50    println!("\n   Combined predicate name:");
51    println!("     Auto-generated name: {:?}", combined.name());
52    println!("     Test 4: {}\n", combined.test(&4));
53}
examples/predicates/always_predicate_demo.rs (line 26)
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}
Source

pub fn set_name(&mut self, name: &str)

Sets the name of this predicate.

§Parameters
  • name - The name to set for this predicate
Examples found in repository?
examples/predicates/predicate_set_name_demo.rs (line 42)
29fn demo_box_predicate() {
30    println!("1. BoxPredicate Naming Functionality");
31
32    // Create a predicate with name using new_with_name
33    let pred1 = BoxPredicate::new_with_name("is_positive", |x: &i32| *x > 0);
34    println!("   Created with new_with_name:");
35    println!("     Name: {:?}", pred1.name());
36    println!("     Test 5: {}", pred1.test(&5));
37
38    // Set name for an existing predicate using set_name
39    let mut pred2 = BoxPredicate::new(|x: &i32| x % 2 == 0);
40    println!("\n   Created with new then set_name:");
41    println!("     Initial name: {:?}", pred2.name());
42    pred2.set_name("is_even");
43    println!("     Name after setting: {:?}", pred2.name());
44    println!("     Test 4: {}", pred2.test(&4));
45
46    // Combined predicates automatically generate new names
47    let pred3 = BoxPredicate::new_with_name("positive", |x: &i32| *x > 0);
48    let pred4 = BoxPredicate::new_with_name("even", |x: &i32| x % 2 == 0);
49    let combined = pred3.and(pred4);
50    println!("\n   Combined predicate name:");
51    println!("     Auto-generated name: {:?}", combined.name());
52    println!("     Test 4: {}\n", combined.test(&4));
53}
Source

pub fn clear_name(&mut self)

Clears the name of this predicate.

Source

pub fn always_true() -> Self

Creates a predicate that always returns true.

§Returns

A new BoxPredicate that always returns true.

Examples found in repository?
examples/predicates/always_predicate_demo.rs (line 21)
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}
Source

pub fn always_false() -> Self

Creates a predicate that always returns false.

§Returns

A new BoxPredicate that always returns false.

Examples found in repository?
examples/predicates/always_predicate_demo.rs (line 29)
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}
Source

pub fn and<P>(self, other: P) -> BoxPredicate<T>
where P: Predicate<T> + 'static, T: 'static,

Returns a predicate that represents the logical AND of this predicate and another.

This method consumes self due to single-ownership semantics.

§Parameters
  • other - The other predicate to combine with.
§Returns

A new predicate representing the logical AND.

Examples found in repository?
examples/predicates/predicate_demo.rs (line 97)
82fn box_predicate_examples() {
83    println!("--- 2. BoxPredicate Examples (Single Ownership) ---");
84
85    // Basic BoxPredicate
86    let pred = BoxPredicate::new(|x: &i32| *x > 0);
87    println!("BoxPredicate test 5: {}", pred.test(&5));
88
89    // Named predicate for better debugging
90    let named_pred = BoxPredicate::new_with_name("is_positive_even", |x: &i32| *x > 0 && x % 2 == 0);
91    println!("Predicate name: {:?}", named_pred.name());
92    println!("Test 4: {}", named_pred.test(&4));
93
94    // Method chaining - consumes self
95    let positive = BoxPredicate::new_with_name("positive", |x: &i32| *x > 0);
96    let even = BoxPredicate::new_with_name("even", |x: &i32| x % 2 == 0);
97    let combined = positive.and(even);
98    println!("Combined predicate name: {:?}", combined.name());
99    println!("Test 4: {}", combined.test(&4));
100}
More examples
Hide additional examples
examples/predicates/predicate_set_name_demo.rs (line 49)
29fn demo_box_predicate() {
30    println!("1. BoxPredicate Naming Functionality");
31
32    // Create a predicate with name using new_with_name
33    let pred1 = BoxPredicate::new_with_name("is_positive", |x: &i32| *x > 0);
34    println!("   Created with new_with_name:");
35    println!("     Name: {:?}", pred1.name());
36    println!("     Test 5: {}", pred1.test(&5));
37
38    // Set name for an existing predicate using set_name
39    let mut pred2 = BoxPredicate::new(|x: &i32| x % 2 == 0);
40    println!("\n   Created with new then set_name:");
41    println!("     Initial name: {:?}", pred2.name());
42    pred2.set_name("is_even");
43    println!("     Name after setting: {:?}", pred2.name());
44    println!("     Test 4: {}", pred2.test(&4));
45
46    // Combined predicates automatically generate new names
47    let pred3 = BoxPredicate::new_with_name("positive", |x: &i32| *x > 0);
48    let pred4 = BoxPredicate::new_with_name("even", |x: &i32| x % 2 == 0);
49    let combined = pred3.and(pred4);
50    println!("\n   Combined predicate name:");
51    println!("     Auto-generated name: {:?}", combined.name());
52    println!("     Test 4: {}\n", combined.test(&4));
53}
examples/predicates/always_predicate_demo.rs (line 81)
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}
Source

pub fn or<P>(self, other: P) -> BoxPredicate<T>
where P: Predicate<T> + 'static, T: 'static,

Returns a predicate that represents the logical OR of this predicate and another.

This method consumes self due to single-ownership semantics.

§Parameters
  • other - The other predicate to combine with.
§Returns

A new predicate representing the logical OR.

Examples found in repository?
examples/predicates/always_predicate_demo.rs (line 98)
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}
Source

pub fn nand<P>(self, other: P) -> BoxPredicate<T>
where P: Predicate<T> + 'static, T: 'static,

Returns a predicate that represents the logical NAND (NOT AND) of this predicate and another.

NAND returns true unless both predicates are true. Equivalent to !(self AND other).

This method consumes self due to single-ownership semantics.

§Parameters
  • other - The other predicate to combine with.
§Returns

A new predicate representing the logical NAND.

Source

pub fn xor<P>(self, other: P) -> BoxPredicate<T>
where P: Predicate<T> + 'static, T: 'static,

Returns a predicate that represents the logical XOR (exclusive OR) of this predicate and another.

XOR returns true if exactly one of the predicates is true.

This method consumes self due to single-ownership semantics.

§Parameters
  • other - The other predicate to combine with.
§Returns

A new predicate representing the logical XOR.

Source

pub fn nor<P>(self, other: P) -> BoxPredicate<T>
where P: Predicate<T> + 'static, T: 'static,

Returns a predicate that represents the logical NOR (NOT OR) of this predicate and another.

NOR returns true only when both predicates are false. Equivalent to !(self OR other).

This method consumes self due to single-ownership semantics.

§Parameters
  • other - The other predicate to combine with.
§Returns

A new predicate representing the logical NOR.

Trait Implementations§

Source§

impl<T> Debug for BoxPredicate<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Display for BoxPredicate<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Not for BoxPredicate<T>
where T: 'static,

Source§

type Output = BoxPredicate<T>

The resulting type after applying the ! operator.
Source§

fn not(self) -> Self::Output

Performs the unary ! operation. Read more
Source§

impl<T> Predicate<T> for BoxPredicate<T>

Source§

fn test(&self, value: &T) -> bool

Tests whether the given value satisfies this predicate. Read more
Source§

fn into_box(self) -> BoxPredicate<T>

Converts this predicate into a BoxPredicate. Read more
Source§

fn into_rc(self) -> RcPredicate<T>
where Self: 'static,

Converts this predicate into an RcPredicate. Read more
Source§

fn into_fn(self) -> impl Fn(&T) -> bool

Converts this predicate into a closure that can be used directly with standard library methods. Read more
Source§

fn into_arc(self) -> ArcPredicate<T>
where Self: Sized + Send + Sync + 'static,

Converts this predicate into an ArcPredicate. Read more

Auto Trait Implementations§

§

impl<T> Freeze for BoxPredicate<T>

§

impl<T> !RefUnwindSafe for BoxPredicate<T>

§

impl<T> !Send for BoxPredicate<T>

§

impl<T> !Sync for BoxPredicate<T>

§

impl<T> Unpin for BoxPredicate<T>

§

impl<T> UnsafeUnpin for BoxPredicate<T>

§

impl<T> !UnwindSafe for BoxPredicate<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.