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