qubit_function/consumers/bi_consumer_once.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026.
4 * Haixing Hu, Qubit Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! # BiConsumerOnce Types
10//!
11//! Provides one-time bi-consumer interface implementations for operations
12//! accepting two input parameters without returning a result.
13//!
14//! It is similar to the `FnOnce(&T, &U)` trait in the standard library.
15//!
16//! This module provides a unified `BiConsumerOnce` trait and one concrete
17//! implementation:
18//!
19//! - **`BoxBiConsumerOnce<T, U>`**: Box-based single ownership
20//! implementation
21//!
22//! # Why No Arc/Rc Variants?
23//!
24//! Unlike `BiConsumer` and `ReadonlyBiConsumer`, this module does **not**
25//! provide `ArcBiConsumerOnce` or `RcBiConsumerOnce` implementations. This
26//! is a design decision based on the fundamental incompatibility between
27//! `FnOnce` semantics and shared ownership. See the design documentation
28//! for details.
29//!
30//! # Design Philosophy
31//!
32//! BiConsumerOnce uses `FnOnce(&T, &U)` semantics: for truly one-time
33//! consumption operations.
34//!
35//! Unlike BiConsumer, BiConsumerOnce consumes itself on first call. Suitable
36//! for initialization callbacks, cleanup callbacks, etc.
37//!
38//! # Author
39//!
40//! Haixing Hu
41use crate::{
42 consumers::macros::{
43 impl_box_conditional_consumer,
44 impl_box_consumer_methods,
45 impl_conditional_consumer_debug_display,
46 impl_consumer_common_methods,
47 impl_consumer_debug_display,
48 },
49 macros::{
50 impl_box_once_conversions,
51 impl_closure_once_trait,
52 },
53 predicates::bi_predicate::{
54 BiPredicate,
55 BoxBiPredicate,
56 },
57};
58
59// ==========================================================================
60// Type Aliases
61// ==========================================================================
62
63/// Type alias for bi-consumer once function signature.
64type BiConsumerOnceFn<T, U> = dyn FnOnce(&T, &U);
65
66// =======================================================================
67// 1. BiConsumerOnce Trait - Unified Interface
68// =======================================================================
69
70/// BiConsumerOnce trait - Unified one-time bi-consumer interface
71///
72/// It is similar to the `FnOnce(&T, &U)` trait in the standard library.
73///
74/// Defines core behavior for all one-time bi-consumer types. Similar to a
75/// bi-consumer implementing `FnOnce(&T, &U)`, performs operations
76/// accepting two value references but returning no result (side effects
77/// only), consuming itself in the process.
78///
79/// # Automatic Implementations
80///
81/// - All closures implementing `FnOnce(&T, &U)`
82/// - `BoxBiConsumerOnce<T, U>`
83///
84/// # Features
85///
86/// - **Unified Interface**: All bi-consumer types share the same `accept`
87/// method signature
88/// - **Automatic Implementation**: Closures automatically implement this
89/// trait with zero overhead
90/// - **Type Conversions**: Can convert to BoxBiConsumerOnce
91/// - **Generic Programming**: Write functions accepting any one-time
92/// bi-consumer type
93///
94/// # Examples
95///
96/// ```rust
97/// use qubit_function::{BiConsumerOnce, BoxBiConsumerOnce};
98/// use std::sync::{Arc, Mutex};
99///
100/// fn apply_consumer<C: BiConsumerOnce<i32, i32>>(
101/// consumer: C,
102/// a: &i32,
103/// b: &i32
104/// ) {
105/// consumer.accept(a, b);
106/// }
107///
108/// let log = Arc::new(Mutex::new(Vec::new()));
109/// let l = log.clone();
110/// let box_con = BoxBiConsumerOnce::new(move |x: &i32, y: &i32| {
111/// l.lock().unwrap().push(*x + *y);
112/// });
113/// apply_consumer(box_con, &5, &3);
114/// assert_eq!(*log.lock().unwrap(), vec![8]);
115/// ```
116///
117/// # Author
118///
119/// Haixing Hu
120pub trait BiConsumerOnce<T, U> {
121 /// Performs the one-time consumption operation
122 ///
123 /// Executes an operation on the given two references. The operation
124 /// typically reads input values or produces side effects, but does not
125 /// modify the input values themselves. Consumes self.
126 ///
127 /// # Parameters
128 ///
129 /// * `first` - Reference to the first value to consume
130 /// * `second` - Reference to the second value to consume
131 ///
132 /// # Examples
133 ///
134 /// ```rust
135 /// use qubit_function::{BiConsumerOnce, BoxBiConsumerOnce};
136 ///
137 /// let consumer = BoxBiConsumerOnce::new(|x: &i32, y: &i32| {
138 /// println!("Sum: {}", x + y);
139 /// });
140 /// consumer.accept(&5, &3);
141 /// ```
142 fn accept(self, first: &T, second: &U);
143
144 /// Converts to BoxBiConsumerOnce
145 ///
146 /// **⚠️ Consumes `self`**: Original consumer becomes unavailable after
147 /// calling this method.
148 ///
149 /// # Returns
150 ///
151 /// Returns the wrapped `BoxBiConsumerOnce<T, U>`
152 ///
153 /// # Examples
154 ///
155 /// ```rust
156 /// use qubit_function::BiConsumerOnce;
157 /// use std::sync::{Arc, Mutex};
158 ///
159 /// let log = Arc::new(Mutex::new(Vec::new()));
160 /// let l = log.clone();
161 /// let closure = move |x: &i32, y: &i32| {
162 /// l.lock().unwrap().push(*x + *y);
163 /// };
164 /// let box_consumer = closure.into_box();
165 /// box_consumer.accept(&5, &3);
166 /// assert_eq!(*log.lock().unwrap(), vec![8]);
167 /// ```
168 fn into_box(self) -> BoxBiConsumerOnce<T, U>
169 where
170 Self: Sized + 'static,
171 {
172 BoxBiConsumerOnce::new(move |t, u| self.accept(t, u))
173 }
174
175 /// Converts to a closure
176 ///
177 /// **⚠️ Consumes `self`**: Original consumer becomes unavailable after
178 /// calling this method.
179 ///
180 /// Converts the one-time bi-consumer to a closure usable with standard
181 /// library methods requiring `FnOnce`.
182 ///
183 /// # Returns
184 ///
185 /// Returns a closure implementing `FnOnce(&T, &U)`
186 fn into_fn(self) -> impl FnOnce(&T, &U)
187 where
188 Self: Sized + 'static,
189 {
190 move |t, u| self.accept(t, u)
191 }
192
193 /// Convert to BoxBiConsumerOnce without consuming self
194 ///
195 /// **⚠️ Requires Clone**: This method requires `Self` to implement
196 /// `Clone`. Clones the current bi-consumer and then converts the clone
197 /// to a `BoxBiConsumerOnce`.
198 ///
199 /// # Returns
200 ///
201 /// Returns the wrapped `BoxBiConsumerOnce<T, U>`
202 ///
203 /// # Examples
204 ///
205 /// ```rust
206 /// use qubit_function::BiConsumerOnce;
207 /// use std::sync::{Arc, Mutex};
208 ///
209 /// let log = Arc::new(Mutex::new(Vec::new()));
210 /// let l = log.clone();
211 /// let closure = move |x: &i32, y: &i32| {
212 /// l.lock().unwrap().push(*x + *y);
213 /// };
214 /// let box_consumer = closure.to_box();
215 /// box_consumer.accept(&5, &3);
216 /// assert_eq!(*log.lock().unwrap(), vec![8]);
217 /// ```
218 fn to_box(&self) -> BoxBiConsumerOnce<T, U>
219 where
220 Self: Sized + Clone + 'static,
221 {
222 self.clone().into_box()
223 }
224
225 /// Convert to closure without consuming self
226 ///
227 /// **⚠️ Requires Clone**: This method requires `Self` to implement
228 /// `Clone`. Clones the current bi-consumer and then converts the clone
229 /// to a closure.
230 ///
231 /// # Returns
232 ///
233 /// Returns a closure implementing `FnOnce(&T, &U)`
234 ///
235 /// # Examples
236 ///
237 /// ```rust
238 /// use qubit_function::BiConsumerOnce;
239 /// use std::sync::{Arc, Mutex};
240 ///
241 /// let log = Arc::new(Mutex::new(Vec::new()));
242 /// let l = log.clone();
243 /// let closure = move |x: &i32, y: &i32| {
244 /// l.lock().unwrap().push(*x + *y);
245 /// };
246 /// let func = closure.to_fn();
247 /// func(&5, &3);
248 /// assert_eq!(*log.lock().unwrap(), vec![8]);
249 /// ```
250 fn to_fn(&self) -> impl FnOnce(&T, &U)
251 where
252 Self: Sized + Clone + 'static,
253 {
254 self.clone().into_fn()
255 }
256}
257
258// =======================================================================
259// 2. BoxBiConsumerOnce - Single Ownership Implementation
260// =======================================================================
261
262/// BoxBiConsumerOnce struct
263///
264/// A one-time bi-consumer implementation based on
265/// `Box<dyn FnOnce(&T, &U)>` for single ownership scenarios. This is the
266/// simplest one-time bi-consumer type for truly one-time use.
267///
268/// # Features
269///
270/// - **Single Ownership**: Not cloneable, ownership moves on use
271/// - **Zero Overhead**: No reference counting or locking
272/// - **One-Time Use**: Consumes self on first call
273/// - **Builder Pattern**: Method chaining consumes `self` naturally
274///
275/// # Use Cases
276///
277/// Choose `BoxBiConsumerOnce` when:
278/// - The bi-consumer is truly used only once
279/// - Building pipelines where ownership naturally flows
280/// - The consumer captures values that should be consumed
281/// - Performance is critical and sharing overhead is unacceptable
282///
283/// # Performance
284///
285/// `BoxBiConsumerOnce` has the best performance:
286/// - No reference counting overhead
287/// - No lock acquisition or runtime borrow checking
288/// - Direct function call through vtable
289/// - Minimal memory footprint (single pointer)
290///
291/// # Examples
292///
293/// ```rust
294/// use qubit_function::{BiConsumerOnce, BoxBiConsumerOnce};
295///
296/// let consumer = BoxBiConsumerOnce::new(|x: &i32, y: &i32| {
297/// println!("Sum: {}", x + y);
298/// });
299/// consumer.accept(&5, &3);
300/// ```
301///
302/// # Author
303///
304/// Haixing Hu
305pub struct BoxBiConsumerOnce<T, U> {
306 function: Box<BiConsumerOnceFn<T, U>>,
307 name: Option<String>,
308}
309
310// All methods require T: 'static and U: 'static because
311// Box<dyn FnOnce(&T, &U)> requires it
312impl<T, U> BoxBiConsumerOnce<T, U> {
313 // Generates: new(), new_with_name(), name(), set_name(), noop()
314 impl_consumer_common_methods!(
315 BoxBiConsumerOnce<T, U>,
316 (FnOnce(&T, &U) + 'static),
317 |f| Box::new(f)
318 );
319
320 // Generates: when() and and_then() methods that consume self
321 impl_box_consumer_methods!(
322 BoxBiConsumerOnce<T, U>,
323 BoxConditionalBiConsumerOnce,
324 BiConsumerOnce
325 );
326}
327
328impl<T, U> BiConsumerOnce<T, U> for BoxBiConsumerOnce<T, U> {
329 fn accept(self, first: &T, second: &U) {
330 (self.function)(first, second)
331 }
332
333 impl_box_once_conversions!(
334 BoxBiConsumerOnce<T, U>,
335 BiConsumerOnce,
336 FnOnce(&T, &U)
337 );
338}
339
340// Use macro to generate Debug and Display implementations
341impl_consumer_debug_display!(BoxBiConsumerOnce<T, U>);
342
343// =======================================================================
344// 3. Implement BiConsumerOnce trait for closures
345// =======================================================================
346
347// Implement BiConsumerOnce for all FnOnce(&T, &U) using macro
348impl_closure_once_trait!(
349 BiConsumerOnce<T, U>,
350 accept,
351 BoxBiConsumerOnce,
352 FnOnce(first: &T, second: &U)
353);
354
355// =======================================================================
356// 4. Provide extension methods for closures
357// =======================================================================
358
359/// Extension trait providing one-time bi-consumer composition methods for
360/// closures
361///
362/// Provides `and_then` and other composition methods for all closures
363/// implementing `FnOnce(&T, &U)`, enabling direct method chaining on
364/// closures without explicit wrapper types.
365///
366/// # Features
367///
368/// - **Natural Syntax**: Chain operations directly on closures
369/// - **Returns BoxBiConsumerOnce**: Composition results can be further
370/// chained
371/// - **Zero Cost**: No overhead when composing closures
372/// - **Automatic Implementation**: All `FnOnce(&T, &U)` closures get
373/// these methods automatically
374///
375/// # Examples
376///
377/// ```rust
378/// use qubit_function::{BiConsumerOnce, FnBiConsumerOnceOps};
379/// use std::sync::{Arc, Mutex};
380///
381/// let log = Arc::new(Mutex::new(Vec::new()));
382/// let l1 = log.clone();
383/// let l2 = log.clone();
384/// let chained = (move |x: &i32, y: &i32| {
385/// l1.lock().unwrap().push(*x + *y);
386/// }).and_then(move |x: &i32, y: &i32| {
387/// l2.lock().unwrap().push(*x * *y);
388/// });
389/// chained.accept(&5, &3);
390/// assert_eq!(*log.lock().unwrap(), vec![8, 15]);
391/// ```
392///
393/// # Author
394///
395/// Haixing Hu
396pub trait FnBiConsumerOnceOps<T, U>: FnOnce(&T, &U) + Sized {
397 /// Chains another one-time bi-consumer in sequence
398 ///
399 /// Returns a new consumer executing the current operation first, then
400 /// the next operation. Consumes the current closure and returns
401 /// `BoxBiConsumerOnce<T, U>`.
402 ///
403 /// # Type Parameters
404 ///
405 /// * `C` - The type of the next consumer
406 ///
407 /// # Parameters
408 ///
409 /// * `next` - The consumer to execute after the current operation. **Note:
410 /// This parameter is passed by value and will transfer ownership.** Since
411 /// `BoxBiConsumerOnce` cannot be cloned, the parameter will be consumed.
412 /// Can be:
413 /// - A closure: `|x: &T, y: &U|`
414 /// - A `BoxBiConsumerOnce<T, U>`
415 /// - Any type implementing `BiConsumerOnce<T, U>`
416 ///
417 /// # Returns
418 ///
419 /// Returns the composed `BoxBiConsumerOnce<T, U>`
420 ///
421 /// # Examples
422 ///
423 /// ```rust
424 /// use qubit_function::{BiConsumerOnce, FnBiConsumerOnceOps};
425 /// use std::sync::{Arc, Mutex};
426 ///
427 /// let log = Arc::new(Mutex::new(Vec::new()));
428 /// let l1 = log.clone();
429 /// let l2 = log.clone();
430 /// let chained = (move |x: &i32, y: &i32| {
431 /// l1.lock().unwrap().push(*x + *y);
432 /// }).and_then(move |x: &i32, y: &i32| {
433 /// l2.lock().unwrap().push(*x * *y);
434 /// }).and_then(|x: &i32, y: &i32| {
435 /// println!("Result: {}, {}", x, y);
436 /// });
437 ///
438 /// chained.accept(&5, &3);
439 /// assert_eq!(*log.lock().unwrap(), vec![8, 15]);
440 /// ```
441 fn and_then<C>(self, next: C) -> BoxBiConsumerOnce<T, U>
442 where
443 Self: 'static,
444 C: BiConsumerOnce<T, U> + 'static,
445 T: 'static,
446 U: 'static,
447 {
448 let first = self;
449 let second = next;
450 BoxBiConsumerOnce::new(move |t, u| {
451 first(t, u);
452 second.accept(t, u);
453 })
454 }
455}
456
457/// Implements FnBiConsumerOnceOps for all closure types
458impl<T, U, F> FnBiConsumerOnceOps<T, U> for F where F: FnOnce(&T, &U) {}
459
460// =======================================================================
461// 5. BoxConditionalBiConsumerOnce - Box-based Conditional BiConsumerOnce
462// =======================================================================
463
464/// BoxConditionalBiConsumerOnce struct
465///
466/// A conditional one-time bi-consumer that only executes when a predicate is satisfied.
467/// Uses `BoxBiConsumerOnce` and `BoxBiPredicate` for single ownership semantics.
468///
469/// This type is typically created by calling `BoxBiConsumerOnce::when()` and is
470/// designed to work with the `or_else()` method to create if-then-else logic.
471///
472/// # Features
473///
474/// - **Single Ownership**: Not cloneable, consumes `self` on use
475/// - **Conditional Execution**: Only consumes when predicate returns `true`
476/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
477/// - **Implements BiConsumerOnce**: Can be used anywhere a `BiConsumerOnce` is expected
478///
479/// # Examples
480///
481/// ## Basic Conditional Execution
482///
483/// ```rust
484/// use qubit_function::{BiConsumerOnce, BoxBiConsumerOnce};
485/// use std::sync::{Arc, Mutex};
486///
487/// let log = Arc::new(Mutex::new(Vec::new()));
488/// let l = log.clone();
489/// let consumer = BoxBiConsumerOnce::new(move |x: &i32, y: &i32| {
490/// l.lock().unwrap().push(*x + *y);
491/// });
492/// let conditional = consumer.when(|x: &i32, y: &i32| *x > 0 && *y > 0);
493///
494/// conditional.accept(&5, &3);
495/// assert_eq!(*log.lock().unwrap(), vec![8]); // Executed
496/// ```
497///
498/// ## With or_else Branch
499///
500/// ```rust
501/// use qubit_function::{BiConsumerOnce, BoxBiConsumerOnce};
502/// use std::sync::{Arc, Mutex};
503///
504/// let log = Arc::new(Mutex::new(Vec::new()));
505/// let l1 = log.clone();
506/// let l2 = log.clone();
507/// let consumer = BoxBiConsumerOnce::new(move |x: &i32, y: &i32| {
508/// l1.lock().unwrap().push(*x + *y);
509/// }).when(|x: &i32, y: &i32| *x > 0 && *y > 0)
510/// .or_else(move |x: &i32, y: &i32| {
511/// l2.lock().unwrap().push(*x * *y);
512/// });
513///
514/// consumer.accept(&5, &3);
515/// assert_eq!(*log.lock().unwrap(), vec![8]); // when branch executed
516/// ```
517///
518/// # Author
519///
520/// Haixing Hu
521pub struct BoxConditionalBiConsumerOnce<T, U> {
522 consumer: BoxBiConsumerOnce<T, U>,
523 predicate: BoxBiPredicate<T, U>,
524}
525
526// Generate and_then and or_else methods using macro
527impl_box_conditional_consumer!(
528 BoxConditionalBiConsumerOnce<T, U>,
529 BoxBiConsumerOnce,
530 BiConsumerOnce
531);
532
533impl<T, U> BiConsumerOnce<T, U> for BoxConditionalBiConsumerOnce<T, U> {
534 fn accept(self, first: &T, second: &U) {
535 if self.predicate.test(first, second) {
536 self.consumer.accept(first, second);
537 }
538 }
539
540 fn into_fn(self) -> impl FnOnce(&T, &U) {
541 let pred = self.predicate;
542 let consumer = self.consumer;
543 move |t: &T, u: &U| {
544 if pred.test(t, u) {
545 consumer.accept(t, u);
546 }
547 }
548 }
549}
550
551// Use macro to generate Debug and Display implementations
552impl_conditional_consumer_debug_display!(BoxConditionalBiConsumerOnce<T, U>);