pub struct BoxConditionalStatefulBiConsumer<T, U> { /* private fields */ }Expand description
BoxConditionalBiConsumer struct
A conditional bi-consumer that only executes when a predicate is satisfied.
Uses BoxStatefulBiConsumer and BoxBiPredicate for single ownership semantics.
This type is typically created by calling BoxStatefulBiConsumer::when() and is
designed to work with the or_else() method to create if-then-else logic.
§Features
- Single Ownership: Not cloneable, consumes
selfon use - Conditional Execution: Only consumes when predicate returns
true - Chainable: Can add
or_elsebranch to create if-then-else logic - Implements BiConsumer: Can be used anywhere a
BiConsumeris expected
§Examples
§Basic Conditional Execution
use qubit_function::{BiConsumer, BoxStatefulBiConsumer, StatefulBiConsumer};
use std::sync::{Arc, Mutex};
let log = Arc::new(Mutex::new(Vec::new()));
let l = log.clone();
let mut consumer = BoxStatefulBiConsumer::new(move |x: &i32, y: &i32| {
l.lock().expect("mutex should not be poisoned").push(*x + *y);
});
let mut conditional = consumer.when(|x: &i32, y: &i32| *x > 0 && *y > 0);
conditional.accept(&5, &3);
assert_eq!(*log.lock().expect("mutex should not be poisoned"), vec![8]); // Executed
conditional.accept(&-5, &3);
assert_eq!(*log.lock().expect("mutex should not be poisoned"), vec![8]); // Not executed§With or_else Branch
use qubit_function::{BiConsumer, BoxStatefulBiConsumer, StatefulBiConsumer};
use std::sync::{Arc, Mutex};
let log = Arc::new(Mutex::new(Vec::new()));
let l1 = log.clone();
let l2 = log.clone();
let mut consumer = BoxStatefulBiConsumer::new(move |x: &i32, y: &i32| {
l1.lock().expect("mutex should not be poisoned").push(*x + *y);
}).when(|x: &i32, y: &i32| *x > 0 && *y > 0)
.or_else(move |x: &i32, y: &i32| {
l2.lock().expect("mutex should not be poisoned").push(*x * *y);
});
consumer.accept(&5, &3);
assert_eq!(*log.lock().expect("mutex should not be poisoned"), vec![8]); // when branch executed
consumer.accept(&-5, &3);
assert_eq!(*log.lock().expect("mutex should not be poisoned"), vec![8, -15]); // or_else branch executedImplementations§
Source§impl<T, U> BoxConditionalStatefulBiConsumer<T, U>
impl<T, U> BoxConditionalStatefulBiConsumer<T, U>
Sourcepub fn and_then<C>(self, next: C) -> BoxStatefulBiConsumer<T, U>where
T: 'static,
U: 'static,
C: StatefulBiConsumer<T, U> + 'static,
pub fn and_then<C>(self, next: C) -> BoxStatefulBiConsumer<T, U>where
T: 'static,
U: 'static,
C: StatefulBiConsumer<T, U> + 'static,
Chains another bi-consumer in sequence
Combines the current conditional bi-consumer with another bi-consumer into a new bi-consumer that implements the following semantics:
When the returned bi-consumer is called with two arguments:
- First, it checks the predicate of this conditional bi-consumer
- If the predicate is satisfied, it executes the internal bi-consumer of this conditional bi-consumer
- Then, regardless of whether the predicate was
satisfied, it unconditionally executes the
nextbi-consumer
In other words, this creates a bi-consumer that conditionally executes the first action (based on the predicate), and then always executes the second action.
§Parameters
next- The next bi-consumer to execute (always executed)
§Returns
Returns a new combined bi-consumer
§Examples
use std::sync::atomic::{AtomicI32, Ordering};
use qubit_function::BoxBiConsumer;
use qubit_function::BiConsumer;
use std::sync::Arc;
let result = Arc::new(AtomicI32::new(0));
let result1 = result.clone();
let result2 = result.clone();
let consumer1 = BoxBiConsumer::new(move |x: &i32, y: &i32| {
result1.fetch_add(x + y, Ordering::SeqCst);
});
let consumer2 = BoxBiConsumer::new(move |x: &i32, y: &i32| {
result2.fetch_add(2 * (x + y), Ordering::SeqCst);
});
let conditional = consumer1.when(|x: &i32, y: &i32| *x > 0 && *y > 0);
let chained = conditional.and_then(consumer2);
chained.accept(&5, &3); // result = (5+3) + 2*(5+3) = 24
let result3 = result.clone();
result3.store(0, Ordering::SeqCst); // reset
chained.accept(&-5, &3); // result = 0 + 2*(-5+3) = -4 (not -8!)Sourcepub fn or_else<C>(self, else_consumer: C) -> BoxStatefulBiConsumer<T, U>where
T: 'static,
U: 'static,
C: StatefulBiConsumer<T, U> + 'static,
pub fn or_else<C>(self, else_consumer: C) -> BoxStatefulBiConsumer<T, U>where
T: 'static,
U: 'static,
C: StatefulBiConsumer<T, U> + 'static,
Adds an else branch
Executes the original bi-consumer when the condition is satisfied, otherwise executes else_consumer.
§Parameters
else_consumer- The bi-consumer for the else branch
§Returns
Returns a new bi-consumer with if-then-else logic
Examples found in repository?
32fn main() {
33 println!("=== BiConsumer Demo ===\n");
34
35 // 1. BoxBiConsumer - Single ownership
36 println!("1. BoxBiConsumer - Single ownership:");
37 let log = Arc::new(Mutex::new(Vec::new()));
38 let l = log.clone();
39 let box_consumer = BoxBiConsumer::new(move |x: &i32, y: &i32| {
40 println!(" Processing: x={}, y={}", x, y);
41 l.lock().expect("mutex should not be poisoned").push(*x + *y);
42 });
43 box_consumer.accept(&10, &5);
44 println!(
45 " Result log: {:?}\n",
46 *log.lock().expect("mutex should not be poisoned")
47 );
48
49 // 2. Method chaining with BoxBiConsumer
50 println!("2. BoxBiConsumer with method chaining:");
51 let log = Arc::new(Mutex::new(Vec::new()));
52 let l1 = log.clone();
53 let l2 = log.clone();
54 let chained = BoxBiConsumer::new(move |x: &i32, y: &i32| {
55 l1.lock().expect("mutex should not be poisoned").push(*x + *y);
56 println!(" After first operation: sum = {}", x + y);
57 })
58 .and_then(move |x: &i32, y: &i32| {
59 l2.lock().expect("mutex should not be poisoned").push(*x * *y);
60 println!(" After second operation: product = {}", x * y);
61 });
62 chained.accept(&5, &3);
63 println!(
64 " Final log: {:?}\n",
65 *log.lock().expect("mutex should not be poisoned")
66 );
67
68 // 3. ArcBiConsumer - Thread-safe shared ownership
69 println!("3. ArcBiConsumer - Thread-safe shared ownership:");
70 let log = Arc::new(Mutex::new(Vec::new()));
71 let l = log.clone();
72 let arc_consumer = ArcBiConsumer::new(move |x: &i32, y: &i32| {
73 l.lock().expect("mutex should not be poisoned").push(*x + *y);
74 println!(" Thread {:?}: sum = {}", thread::current().id(), x + y);
75 });
76
77 let consumer1 = arc_consumer.clone();
78 let consumer2 = arc_consumer.clone();
79
80 let handle1 = thread::spawn(move || {
81 let c = consumer1;
82 c.accept(&10, &5);
83 });
84
85 let handle2 = thread::spawn(move || {
86 let c = consumer2;
87 c.accept(&20, &8);
88 });
89
90 handle1.join().expect("thread should not panic");
91 handle2.join().expect("thread should not panic");
92 println!(
93 " Final log: {:?}\n",
94 *log.lock().expect("mutex should not be poisoned")
95 );
96
97 // 4. RcBiConsumer - Single-threaded shared ownership
98 println!("4. RcBiConsumer - Single-threaded shared ownership:");
99 let log = Rc::new(RefCell::new(Vec::new()));
100 let l = log.clone();
101 let rc_consumer = RcBiConsumer::new(move |x: &i32, y: &i32| {
102 l.borrow_mut().push(*x + *y);
103 });
104
105 let clone1 = rc_consumer.clone();
106 let clone2 = rc_consumer.clone();
107
108 clone1.accept(&5, &3);
109 println!(" After first use: {:?}", *log.borrow());
110
111 clone2.accept(&7, &2);
112 println!(" After second use: {:?}\n", *log.borrow());
113
114 // 5. Working with closures directly
115 println!("5. Working with closures directly:");
116 let log = Arc::new(Mutex::new(Vec::new()));
117 let l = log.clone();
118 let closure = move |x: &i32, y: &i32| {
119 let sum = *x + *y;
120 l.lock().expect("mutex should not be poisoned").push(sum);
121 };
122 closure.accept(&10, &20);
123 println!(
124 " After closure: {:?}\n",
125 *log.lock().expect("mutex should not be poisoned")
126 );
127
128 // 6. Conditional BiConsumer
129 println!("6. Conditional BiConsumer:");
130 let log = Arc::new(Mutex::new(Vec::new()));
131 let l = log.clone();
132 let mut conditional = BoxStatefulBiConsumer::new(move |x: &i32, y: &i32| {
133 l.lock().expect("mutex should not be poisoned").push(*x + *y);
134 })
135 .when(|x: &i32, y: &i32| *x > 0 && *y > 0);
136
137 conditional.accept(&5, &3);
138 println!(
139 " Positive values: {:?}",
140 *log.lock().expect("mutex should not be poisoned")
141 );
142
143 conditional.accept(&-5, &3);
144 println!(
145 " Negative value (unchanged): {:?}\n",
146 *log.lock().expect("mutex should not be poisoned")
147 );
148
149 // 7. Conditional branch BiConsumer
150 println!("7. Conditional branch BiConsumer:");
151 let log = Arc::new(Mutex::new(Vec::new()));
152 let l1 = log.clone();
153 let l2 = log.clone();
154 let mut branch = BoxStatefulBiConsumer::new(move |x: &i32, _y: &i32| {
155 l1.lock().expect("mutex should not be poisoned").push(*x);
156 })
157 .when(|x: &i32, y: &i32| *x > *y)
158 .or_else(move |_x: &i32, y: &i32| {
159 l2.lock().expect("mutex should not be poisoned").push(*y);
160 });
161
162 branch.accept(&15, &10);
163 println!(" When x > y: {:?}", *log.lock().expect("mutex should not be poisoned"));
164
165 branch.accept(&5, &10);
166 println!(
167 " When x <= y: {:?}\n",
168 *log.lock().expect("mutex should not be poisoned")
169 );
170
171 // 8. Accumulating statistics
172 println!("8. Accumulating statistics:");
173 let count = Arc::new(Mutex::new(0));
174 let sum = Arc::new(Mutex::new(0));
175 let c = count.clone();
176 let s = sum.clone();
177 let stats_consumer = BoxBiConsumer::new(move |x: &i32, y: &i32| {
178 *c.lock().expect("mutex should not be poisoned") += 1;
179 *s.lock().expect("mutex should not be poisoned") += x + y;
180 });
181
182 stats_consumer.accept(&5, &3);
183 stats_consumer.accept(&10, &2);
184 stats_consumer.accept(&7, &8);
185
186 println!(" Count: {}", *count.lock().expect("mutex should not be poisoned"));
187 println!(" Sum: {}\n", *sum.lock().expect("mutex should not be poisoned"));
188
189 // 9. Name support
190 println!("9. Name support:");
191 let mut named_consumer = BoxBiConsumer::<i32, i32>::noop();
192 println!(" Initial name: {:?}", named_consumer.name());
193
194 named_consumer.set_name("sum_calculator");
195 println!(" After setting name: {:?}", named_consumer.name());
196 println!(" Display: {}\n", named_consumer);
197
198 println!("=== Demo Complete ===");
199}