qubit_function/consumers/stateful_consumer.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026.
4 * Haixing Hu, Qubit Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! # Consumer Types
10//!
11//! Provides implementations of consumer interfaces for executing operations
12//! that accept a single input parameter but return no result.
13//!
14//! It is similar to the `FnMut(&T)` trait in the standard library.
15//!
16//! This module provides a unified `Consumer` trait and three concrete
17//! implementations based on different ownership models:
18//!
19//! - **`BoxStatefulConsumer<T>`**: Box-based single ownership implementation for
20//! one-time use scenarios
21//! - **`ArcStatefulConsumer<T>`**: Thread-safe shared ownership implementation
22//! based on Arc<Mutex<>>
23//! - **`RcStatefulConsumer<T>`**: Single-threaded shared ownership implementation
24//! based on Rc<RefCell<>>
25//!
26//! # Design Philosophy
27//!
28//! Consumer uses `FnMut(&T)` semantics, allowing modification of its own state
29//! but not the input value.
30//!
31//! Suitable for statistics, accumulation, event handling, and other scenarios.
32//!
33//! # Author
34//!
35//! Haixing Hu
36use std::cell::RefCell;
37use std::rc::Rc;
38use std::sync::Arc;
39
40use parking_lot::Mutex;
41
42use crate::consumers::consumer_once::BoxConsumerOnce;
43use crate::consumers::macros::{
44 impl_box_conditional_consumer,
45 impl_box_consumer_methods,
46 impl_conditional_consumer_clone,
47 impl_conditional_consumer_conversions,
48 impl_conditional_consumer_debug_display,
49 impl_consumer_clone,
50 impl_consumer_common_methods,
51 impl_consumer_debug_display,
52 impl_shared_conditional_consumer,
53 impl_shared_consumer_methods,
54};
55use crate::macros::{
56 impl_arc_conversions,
57 impl_box_conversions,
58 impl_closure_trait,
59 impl_rc_conversions,
60};
61use crate::predicates::predicate::{
62 ArcPredicate,
63 BoxPredicate,
64 Predicate,
65 RcPredicate,
66};
67
68// ============================================================================
69// 1. Consumer Trait - Unified Consumer Interface
70// ============================================================================
71
72/// Consumer trait - Unified consumer interface
73///
74/// Defines the core behavior of all consumer types. Similar to Java's
75/// `Consumer<T>` interface, executes operations that accept a value but return
76/// no result (side effects only).
77///
78/// It is similar to the `FnMut(&T)` trait in the standard library.
79///
80/// Consumer can modify its own state (such as accumulation, counting), but
81/// should not modify the consumed value itself.
82///
83/// # Automatic Implementation
84///
85/// - All closures implementing `FnMut(&T)`
86/// - `BoxStatefulConsumer<T>`, `ArcStatefulConsumer<T>`, `RcStatefulConsumer<T>`
87///
88/// # Features
89///
90/// - **Unified Interface**: All consumer types share the same `accept` method
91/// signature
92/// - **Automatic Implementation**: Closures automatically implement this trait
93/// with zero overhead
94/// - **Type Conversion**: Easy conversion between different ownership models
95/// - **Generic Programming**: Write functions that work with any consumer type
96///
97/// # Examples
98///
99/// ```rust
100/// use qubit_function::{Consumer, BoxStatefulConsumer, ArcStatefulConsumer};
101/// use std::sync::{Arc, Mutex};
102///
103/// fn apply_consumer<C: StatefulConsumer<i32>>(consumer: &mut C, value: &i32) {
104/// consumer.accept(value);
105/// }
106///
107/// // Works with any consumer type
108/// let log = Arc::new(Mutex::new(Vec::new()));
109/// let l = log.clone();
110/// let mut box_con = BoxStatefulConsumer::new(move |x: &i32| {
111/// l.lock().unwrap().push(*x);
112/// });
113/// apply_consumer(&mut box_con, &5);
114/// assert_eq!(*log.lock().unwrap(), vec![5]);
115/// ```
116///
117/// # Author
118///
119/// Haixing Hu
120pub trait StatefulConsumer<T> {
121 /// Execute consumption operation
122 ///
123 /// Performs an operation on the given reference. The operation typically
124 /// reads the input value or produces side effects, but does not modify the
125 /// input value itself. Can modify the consumer's own state.
126 ///
127 /// # Parameters
128 ///
129 /// * `value` - Reference to the value to be consumed
130 ///
131 /// # Examples
132 ///
133 /// ```rust
134 /// use qubit_function::{Consumer, BoxStatefulConsumer};
135 ///
136 /// let mut consumer = BoxStatefulConsumer::new(|x: &i32| println!("{}", x));
137 /// let value = 5;
138 /// consumer.accept(&value);
139 /// ```
140 fn accept(&mut self, value: &T);
141
142 /// Convert to BoxStatefulConsumer
143 ///
144 /// **⚠️ Consumes `self`**: The original consumer will be unavailable after
145 /// calling this method.
146 ///
147 /// Converts the current consumer to `BoxStatefulConsumer<T>`.
148 ///
149 /// # Ownership
150 ///
151 /// This method **consumes** the consumer (takes ownership of `self`).
152 /// After calling this method, the original consumer is no longer available.
153 ///
154 /// **Tip**: For cloneable consumers ([`ArcStatefulConsumer`], [`RcStatefulConsumer`]),
155 /// if you need to preserve the original object, you can call `.clone()`
156 /// first.
157 ///
158 /// # Return Value
159 ///
160 /// Returns the wrapped `BoxStatefulConsumer<T>`
161 ///
162 /// # Examples
163 ///
164 /// ```rust
165 /// use qubit_function::Consumer;
166 /// use std::sync::{Arc, Mutex};
167 ///
168 /// let log = Arc::new(Mutex::new(Vec::new()));
169 /// let l = log.clone();
170 /// let closure = move |x: &i32| {
171 /// l.lock().unwrap().push(*x);
172 /// };
173 /// let mut box_consumer = closure.into_box();
174 /// box_consumer.accept(&5);
175 /// assert_eq!(*log.lock().unwrap(), vec![5]);
176 /// ```
177 fn into_box(self) -> BoxStatefulConsumer<T>
178 where
179 Self: Sized + 'static,
180 T: 'static,
181 {
182 let mut consumer = self;
183 BoxStatefulConsumer::new(move |t| consumer.accept(t))
184 }
185
186 /// Convert to RcStatefulConsumer
187 ///
188 /// **⚠️ Consumes `self`**: The original consumer will be unavailable after
189 /// calling this method.
190 ///
191 /// # Return Value
192 ///
193 /// Returns the wrapped `RcStatefulConsumer<T>`
194 fn into_rc(self) -> RcStatefulConsumer<T>
195 where
196 Self: Sized + 'static,
197 T: 'static,
198 {
199 let mut consumer = self;
200 RcStatefulConsumer::new(move |t| consumer.accept(t))
201 }
202
203 /// Convert to ArcStatefulConsumer
204 ///
205 /// **⚠️ Consumes `self`**: The original consumer will be unavailable after
206 /// calling this method.
207 ///
208 /// # Return Value
209 ///
210 /// Returns the wrapped `ArcStatefulConsumer<T>`
211 fn into_arc(self) -> ArcStatefulConsumer<T>
212 where
213 Self: Sized + Send + 'static,
214 T: 'static,
215 {
216 let mut consumer = self;
217 ArcStatefulConsumer::new(move |t| consumer.accept(t))
218 }
219
220 /// Convert to closure
221 ///
222 /// **⚠️ Consumes `self`**: The original consumer will be unavailable after
223 /// calling this method.
224 ///
225 /// Converts the consumer to a closure that can be used directly in standard
226 /// library functions requiring `FnMut`.
227 ///
228 /// # Return Value
229 ///
230 /// Returns a closure implementing `FnMut(&T)`
231 ///
232 /// # Examples
233 ///
234 /// ```rust
235 /// use qubit_function::{Consumer, BoxStatefulConsumer};
236 /// use std::sync::{Arc, Mutex};
237 ///
238 /// let log = Arc::new(Mutex::new(Vec::new()));
239 /// let l = log.clone();
240 /// let consumer = BoxStatefulConsumer::new(move |x: &i32| {
241 /// l.lock().unwrap().push(*x);
242 /// });
243 /// let mut func = consumer.into_fn();
244 /// func(&5);
245 /// assert_eq!(*log.lock().unwrap(), vec![5]);
246 /// ```
247 fn into_fn(self) -> impl FnMut(&T)
248 where
249 Self: Sized + 'static,
250 {
251 let mut consumer = self;
252 move |t| consumer.accept(t)
253 }
254
255 /// Convert to ConsumerOnce
256 ///
257 /// **⚠️ Consumes `self`**: The original consumer will be unavailable after calling this method.
258 ///
259 /// Converts a reusable stateful consumer to a one-time consumer that consumes itself on use.
260 /// This enables passing `StatefulConsumer` to functions that require `ConsumerOnce`.
261 ///
262 /// # Returns
263 ///
264 /// Returns a `BoxConsumerOnce<T>`
265 ///
266 /// # Examples
267 ///
268 /// ```rust
269 ///
270 /// fn takes_once<C: ConsumerOnce<i32>>(consumer: C, value: &i32) {
271 /// consumer.accept(value);
272 /// }
273 ///
274 /// let consumer = BoxStatefulConsumer::new(|x: &i32| println!("{}", x));
275 /// takes_once(consumer.into_once(), &5);
276 /// ```
277 fn into_once(self) -> BoxConsumerOnce<T>
278 where
279 Self: Sized + 'static,
280 T: 'static,
281 {
282 BoxConsumerOnce::new(move |t| {
283 let mut consumer = self;
284 consumer.accept(t);
285 })
286 }
287
288 /// Convert to BoxStatefulConsumer
289 ///
290 /// **⚠️ Requires Clone**: The original consumer must implement Clone.
291 ///
292 /// Converts the current consumer to `BoxStatefulConsumer<T>` by cloning it first.
293 ///
294 /// # Ownership
295 ///
296 /// This method does **not consume** the consumer. It clones the consumer and
297 /// then converts the clone to `BoxStatefulConsumer<T>`. The original consumer remains
298 /// available after calling this method.
299 ///
300 /// # Return Value
301 ///
302 /// Returns the wrapped `BoxStatefulConsumer<T>` from the clone
303 ///
304 /// # Examples
305 ///
306 /// ```rust
307 /// use qubit_function::{Consumer, ArcStatefulConsumer};
308 /// use std::sync::{Arc, Mutex};
309 ///
310 /// let log = Arc::new(Mutex::new(Vec::new()));
311 /// let l = log.clone();
312 /// let consumer = ArcStatefulConsumer::new(move |x: &i32| {
313 /// l.lock().unwrap().push(*x);
314 /// });
315 /// let mut box_consumer = consumer.to_box();
316 /// box_consumer.accept(&5);
317 /// assert_eq!(*log.lock().unwrap(), vec![5]);
318 /// // Original consumer still usable
319 /// consumer.accept(&3);
320 /// assert_eq!(*log.lock().unwrap(), vec![5, 3]);
321 /// ```
322 fn to_box(&self) -> BoxStatefulConsumer<T>
323 where
324 Self: Sized + Clone + 'static,
325 T: 'static,
326 {
327 self.clone().into_box()
328 }
329
330 /// Convert to RcStatefulConsumer
331 ///
332 /// **⚠️ Requires Clone**: The original consumer must implement Clone.
333 ///
334 /// Converts the current consumer to `RcStatefulConsumer<T>` by cloning it first.
335 ///
336 /// # Ownership
337 ///
338 /// This method does **not consume** the consumer. It clones the consumer and
339 /// then converts the clone to `RcStatefulConsumer<T>`. The original consumer remains
340 /// available after calling this method.
341 ///
342 /// # Return Value
343 ///
344 /// Returns the wrapped `RcStatefulConsumer<T>` from the clone
345 ///
346 /// # Examples
347 ///
348 /// ```rust
349 /// use qubit_function::{Consumer, ArcStatefulConsumer};
350 /// use std::sync::{Arc, Mutex};
351 ///
352 /// let log = Arc::new(Mutex::new(Vec::new()));
353 /// let l = log.clone();
354 /// let consumer = ArcStatefulConsumer::new(move |x: &i32| {
355 /// l.lock().unwrap().push(*x);
356 /// });
357 /// let mut rc_consumer = consumer.to_rc();
358 /// rc_consumer.accept(&5);
359 /// assert_eq!(*log.lock().unwrap(), vec![5]);
360 /// // Original consumer still usable
361 /// consumer.accept(&3);
362 /// assert_eq!(*log.lock().unwrap(), vec![5, 3]);
363 /// ```
364 fn to_rc(&self) -> RcStatefulConsumer<T>
365 where
366 Self: Sized + Clone + 'static,
367 T: 'static,
368 {
369 self.clone().into_rc()
370 }
371
372 /// Convert to ArcStatefulConsumer
373 ///
374 /// **⚠️ Requires Clone + Send**: The original consumer must implement
375 /// Clone + Send.
376 ///
377 /// Converts the current consumer to `ArcStatefulConsumer<T>` by cloning it first.
378 ///
379 /// # Ownership
380 ///
381 /// This method does **not consume** the consumer. It clones the consumer and
382 /// then converts the clone to `ArcStatefulConsumer<T>`. The original consumer remains
383 /// available after calling this method.
384 ///
385 /// # Return Value
386 ///
387 /// Returns the wrapped `ArcStatefulConsumer<T>` from the clone
388 ///
389 /// # Examples
390 ///
391 /// ```rust
392 /// use qubit_function::{Consumer, RcStatefulConsumer};
393 /// use std::rc::Rc;
394 /// use std::cell::RefCell;
395 ///
396 /// let log = Rc::new(RefCell::new(Vec::new()));
397 /// let l = log.clone();
398 /// let consumer = RcStatefulConsumer::new(move |x: &i32| {
399 /// l.borrow_mut().push(*x);
400 /// });
401 /// let mut arc_consumer = consumer.to_arc();
402 /// arc_consumer.accept(&5);
403 /// assert_eq!(*log.borrow(), vec![5]);
404 /// // Original consumer still usable
405 /// consumer.accept(&3);
406 /// assert_eq!(*log.borrow(), vec![5, 3]);
407 /// ```
408 fn to_arc(&self) -> ArcStatefulConsumer<T>
409 where
410 Self: Sized + Clone + Send + 'static,
411 T: 'static,
412 {
413 self.clone().into_arc()
414 }
415
416 /// Convert to closure
417 ///
418 /// **⚠️ Requires Clone**: The original consumer must implement Clone.
419 ///
420 /// Converts the consumer to a closure that can be used directly in standard
421 /// library functions requiring `FnMut`.
422 ///
423 /// # Ownership
424 ///
425 /// This method does **not consume** the consumer. It clones the consumer and
426 /// then converts the clone to a closure. The original consumer remains
427 /// available after calling this method.
428 ///
429 /// # Return Value
430 ///
431 /// Returns a closure implementing `FnMut(&T)` from the clone
432 ///
433 /// # Examples
434 ///
435 /// ```rust
436 /// use qubit_function::{Consumer, BoxStatefulConsumer};
437 /// use std::sync::{Arc, Mutex};
438 ///
439 /// let log = Arc::new(Mutex::new(Vec::new()));
440 /// let l = log.clone();
441 /// let consumer = BoxStatefulConsumer::new(move |x: &i32| {
442 /// l.lock().unwrap().push(*x);
443 /// });
444 /// let mut func = consumer.to_fn();
445 /// func(&5);
446 /// assert_eq!(*log.lock().unwrap(), vec![5]);
447 /// // Original consumer still usable
448 /// consumer.accept(&3);
449 /// assert_eq!(*log.lock().unwrap(), vec![5, 3]);
450 /// ```
451 fn to_fn(&self) -> impl FnMut(&T)
452 where
453 Self: Sized + Clone + 'static,
454 {
455 self.clone().into_fn()
456 }
457
458 /// Convert to ConsumerOnce without consuming self
459 ///
460 /// **⚠️ Requires Clone**: This method requires `Self` to implement `Clone`.
461 /// Clones the current consumer and converts the clone to a one-time consumer.
462 ///
463 /// # Returns
464 ///
465 /// Returns a `BoxConsumerOnce<T>`
466 ///
467 /// # Examples
468 ///
469 /// ```rust
470 ///
471 /// fn takes_once<C: ConsumerOnce<i32>>(consumer: C, value: &i32) {
472 /// consumer.accept(value);
473 /// }
474 ///
475 /// let consumer = BoxStatefulConsumer::new(|x: &i32| println!("{}", x));
476 /// takes_once(consumer.to_once(), &5);
477 /// ```
478 fn to_once(&self) -> BoxConsumerOnce<T>
479 where
480 Self: Clone + 'static,
481 T: 'static,
482 {
483 self.clone().into_once()
484 }
485}
486
487// ============================================================================
488// 2. BoxStatefulConsumer - Single Ownership Implementation
489// ============================================================================
490
491/// BoxStatefulConsumer struct
492///
493/// Consumer implementation based on `Box<dyn FnMut(&T)>` for single ownership
494/// scenarios. When sharing is not needed, this is the simplest and most
495/// efficient consumer type.
496///
497/// # Features
498///
499/// - **Single Ownership**: Not cloneable, transfers ownership when used
500/// - **Zero Overhead**: No reference counting or lock overhead
501/// - **Mutable State**: Can modify captured environment through `FnMut`
502/// - **Builder Pattern**: Method chaining naturally consumes `self`
503///
504/// # Use Cases
505///
506/// Choose `BoxStatefulConsumer` when:
507/// - Consumer is used only once or in a linear flow
508/// - Building pipelines where ownership flows naturally
509/// - No need to share consumers across contexts
510/// - Performance critical and cannot accept sharing overhead
511///
512/// # Performance
513///
514/// `BoxStatefulConsumer` has the best performance among the three consumer types:
515/// - No reference counting overhead
516/// - No lock acquisition or runtime borrowing checks
517/// - Direct function calls through vtable
518/// - Minimal memory footprint (single pointer)
519///
520/// # Examples
521///
522/// ```rust
523/// use qubit_function::{Consumer, BoxStatefulConsumer};
524/// use std::sync::{Arc, Mutex};
525///
526/// let log = Arc::new(Mutex::new(Vec::new()));
527/// let l = log.clone();
528/// let mut consumer = BoxStatefulConsumer::new(move |x: &i32| {
529/// l.lock().unwrap().push(*x);
530/// });
531/// consumer.accept(&5);
532/// assert_eq!(*log.lock().unwrap(), vec![5]);
533/// ```
534///
535/// # Author
536///
537/// Haixing Hu
538pub struct BoxStatefulConsumer<T> {
539 function: Box<dyn FnMut(&T)>,
540 name: Option<String>,
541}
542
543impl<T> BoxStatefulConsumer<T> {
544 // Generates: new(), new_with_name(), name(), set_name(), noop()
545 impl_consumer_common_methods!(BoxStatefulConsumer<T>, (FnMut(&T) + 'static), |f| Box::new(
546 f
547 ));
548
549 // Generates: when() and and_then() methods that consume self
550 impl_box_consumer_methods!(
551 BoxStatefulConsumer<T>,
552 BoxConditionalStatefulConsumer,
553 StatefulConsumer
554 );
555}
556
557impl<T> StatefulConsumer<T> for BoxStatefulConsumer<T> {
558 fn accept(&mut self, value: &T) {
559 (self.function)(value)
560 }
561
562 // Generates: into_box(), into_rc(), into_fn(), into_once()
563 impl_box_conversions!(
564 BoxStatefulConsumer<T>,
565 RcStatefulConsumer,
566 FnMut(&T),
567 BoxConsumerOnce
568 );
569}
570
571// Use macro to generate Debug and Display implementations
572impl_consumer_debug_display!(BoxStatefulConsumer<T>);
573
574// ============================================================================
575// 3. RcStatefulConsumer - Single-Threaded Shared Ownership Implementation
576// ============================================================================
577
578/// RcStatefulConsumer struct
579///
580/// Consumer implementation based on `Rc<RefCell<dyn FnMut(&T)>>` for
581/// single-threaded shared ownership scenarios. This consumer provides the
582/// benefits of shared ownership without the overhead of thread safety.
583///
584/// # Features
585///
586/// - **Shared Ownership**: Cloneable through `Rc`, allowing multiple owners
587/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
588/// - **Interior Mutability**: Uses `RefCell` for runtime borrowing checks
589/// - **No Lock Overhead**: More efficient than `ArcStatefulConsumer` for single-threaded
590/// use
591/// - **Non-Consuming API**: `and_then` borrows `&self`, original object remains
592/// usable
593///
594/// # Use Cases
595///
596/// Choose `RcStatefulConsumer` when:
597/// - Need to share consumers within a single thread
598/// - Thread safety is not needed
599/// - Performance is important (avoid lock overhead)
600/// - UI event handling in single-threaded frameworks
601/// - Building complex single-threaded state machines
602///
603/// # Performance Considerations
604///
605/// `RcStatefulConsumer` performs better than `ArcStatefulConsumer` in single-threaded scenarios:
606/// - **Non-Atomic Counting**: clone/drop is cheaper than `Arc`
607/// - **No Lock Overhead**: `RefCell` uses runtime checks, no locks
608/// - **Better Cache Locality**: No atomic operations means better CPU cache
609/// behavior
610///
611/// But still has slight overhead compared to `BoxStatefulConsumer`:
612/// - **Reference Counting**: Non-atomic but still exists
613/// - **Runtime Borrowing Checks**: `RefCell` checks at runtime
614///
615/// # Safety
616///
617/// `RcStatefulConsumer` is not thread-safe and does not implement `Send` or `Sync`.
618/// Attempting to send it to another thread will result in a compilation error.
619/// For thread-safe sharing, use `ArcStatefulConsumer` instead.
620///
621/// # Examples
622///
623/// ```rust
624/// use qubit_function::{Consumer, RcStatefulConsumer};
625/// use std::rc::Rc;
626/// use std::cell::RefCell;
627///
628/// let log = Rc::new(RefCell::new(Vec::new()));
629/// let l = log.clone();
630/// let mut consumer = RcStatefulConsumer::new(move |x: &i32| {
631/// l.borrow_mut().push(*x * 2);
632/// });
633/// let mut clone = consumer.clone();
634///
635/// consumer.accept(&5);
636/// assert_eq!(*log.borrow(), vec![10]);
637/// ```
638///
639/// # Author
640///
641/// Haixing Hu
642pub struct RcStatefulConsumer<T> {
643 function: Rc<RefCell<dyn FnMut(&T)>>,
644 name: Option<String>,
645}
646
647impl<T> RcStatefulConsumer<T> {
648 // Generates: new(), new_with_name(), name(), set_name(), noop()
649 impl_consumer_common_methods!(RcStatefulConsumer<T>, (FnMut(&T) + 'static), |f| Rc::new(
650 RefCell::new(f)
651 ));
652
653 // Generates: when() and and_then() methods that borrow &self (Rc can clone)
654 impl_shared_consumer_methods!(
655 RcStatefulConsumer<T>,
656 RcConditionalStatefulConsumer,
657 into_rc,
658 StatefulConsumer,
659 'static
660 );
661}
662
663impl<T> StatefulConsumer<T> for RcStatefulConsumer<T> {
664 fn accept(&mut self, value: &T) {
665 (self.function.borrow_mut())(value)
666 }
667
668 // Use macro to implement conversion methods
669 impl_rc_conversions!(
670 RcStatefulConsumer<T>,
671 BoxStatefulConsumer,
672 BoxConsumerOnce,
673 FnMut(t: &T)
674 );
675}
676
677// Use macro to generate Clone implementation
678impl_consumer_clone!(RcStatefulConsumer<T>);
679
680// Use macro to generate Debug and Display implementations
681impl_consumer_debug_display!(RcStatefulConsumer<T>);
682
683// ============================================================================
684// 4. ArcStatefulConsumer - Thread-Safe Shared Ownership Implementation
685// ============================================================================
686
687/// ArcStatefulConsumer struct
688///
689/// Consumer implementation based on `Arc<Mutex<dyn FnMut(&T) + Send>>` for
690/// thread-safe shared ownership scenarios. This consumer can be safely cloned
691/// and shared across multiple threads.
692///
693/// # Features
694///
695/// - **Shared Ownership**: Cloneable through `Arc`, allowing multiple owners
696/// - **Thread Safety**: Implements `Send + Sync`, safe for concurrent use
697/// - **Interior Mutability**: Uses `Mutex` for safe mutable access
698/// - **Non-Consuming API**: `and_then` borrows `&self`, original object remains
699/// usable
700/// - **Cross-Thread Sharing**: Can be sent to other threads and used
701///
702/// # Use Cases
703///
704/// Choose `ArcStatefulConsumer` when:
705/// - Need to share consumers across multiple threads
706/// - Concurrent task processing (e.g., thread pools)
707/// - Using the same consumer in multiple places simultaneously
708/// - Need thread safety (Send + Sync)
709///
710/// # Performance Considerations
711///
712/// `ArcStatefulConsumer` has some performance overhead compared to `BoxStatefulConsumer`:
713/// - **Reference Counting**: Atomic operations on clone/drop
714/// - **Mutex Locking**: Each `accept` call requires lock acquisition
715/// - **Lock Contention**: High concurrency may cause contention
716///
717/// These overheads are necessary for safe concurrent access. If thread safety
718/// is not needed, consider using `RcStatefulConsumer` for less single-threaded sharing
719/// overhead.
720///
721/// # Examples
722///
723/// ```rust
724/// use qubit_function::{Consumer, ArcStatefulConsumer};
725/// use std::sync::{Arc, Mutex};
726///
727/// let log = Arc::new(Mutex::new(Vec::new()));
728/// let l = log.clone();
729/// let mut consumer = ArcStatefulConsumer::new(move |x: &i32| {
730/// l.lock().unwrap().push(*x * 2);
731/// });
732/// let mut clone = consumer.clone();
733///
734/// consumer.accept(&5);
735/// assert_eq!(*log.lock().unwrap(), vec![10]);
736/// ```
737///
738/// # Author
739///
740/// Haixing Hu
741pub struct ArcStatefulConsumer<T> {
742 function: Arc<Mutex<dyn FnMut(&T) + Send>>,
743 name: Option<String>,
744}
745
746impl<T> ArcStatefulConsumer<T> {
747 // Generates: new(), new_with_name(), name(), set_name(), noop()
748 impl_consumer_common_methods!(ArcStatefulConsumer<T>, (FnMut(&T) + Send + 'static), |f| {
749 Arc::new(Mutex::new(f))
750 });
751
752 // Generates: when() and and_then() methods that borrow &self (Arc can clone)
753 impl_shared_consumer_methods!(
754 ArcStatefulConsumer<T>,
755 ArcConditionalStatefulConsumer,
756 into_arc,
757 StatefulConsumer,
758 Send + Sync + 'static
759 );
760}
761
762impl<T> StatefulConsumer<T> for ArcStatefulConsumer<T> {
763 fn accept(&mut self, value: &T) {
764 (self.function.lock())(value)
765 }
766
767 // Use macro to implement conversion methods
768 impl_arc_conversions!(
769 ArcStatefulConsumer<T>,
770 BoxStatefulConsumer,
771 RcStatefulConsumer,
772 BoxConsumerOnce,
773 FnMut(t: &T)
774 );
775}
776
777// Use macro to generate Clone implementation
778impl_consumer_clone!(ArcStatefulConsumer<T>);
779
780// Use macro to generate Debug and Display implementations
781impl_consumer_debug_display!(ArcStatefulConsumer<T>);
782
783// ============================================================================
784// 5. Implement Consumer trait for closures
785// ============================================================================
786
787// Implement Consumer for all FnMut(&T)
788impl_closure_trait!(
789 StatefulConsumer<T>,
790 accept,
791 BoxConsumerOnce,
792 FnMut(value: &T)
793);
794
795// ============================================================================
796// 6. Extension methods for closures
797// ============================================================================
798
799/// Extension trait providing consumer composition methods for closures
800///
801/// Provides `and_then` and other composition methods for all closures
802/// implementing `FnMut(&T)`, allowing direct method chaining on closures
803/// without explicit wrapper types.
804///
805/// # Design Philosophy
806///
807/// This trait allows closures to be naturally composed using method syntax,
808/// similar to iterator combinators. Composition methods consume the closure and
809/// return `BoxStatefulConsumer<T>`, which can continue chaining.
810///
811/// # Features
812///
813/// - **Natural Syntax**: Direct method chaining on closures
814/// - **Returns BoxStatefulConsumer**: Composition results in `BoxStatefulConsumer<T>`, can
815/// continue chaining
816/// - **Zero Cost**: No overhead when composing closures
817/// - **Automatic Implementation**: All `FnMut(&T)` closures automatically get
818/// these methods
819///
820/// # Examples
821///
822/// ```rust
823/// use qubit_function::{Consumer, FnStatefulConsumerOps};
824/// use std::sync::{Arc, Mutex};
825///
826/// let log = Arc::new(Mutex::new(Vec::new()));
827/// let l1 = log.clone();
828/// let l2 = log.clone();
829/// let mut chained = (move |x: &i32| {
830/// l1.lock().unwrap().push(*x * 2);
831/// }).and_then(move |x: &i32| {
832/// l2.lock().unwrap().push(*x + 10);
833/// });
834/// chained.accept(&5);
835/// assert_eq!(*log.lock().unwrap(), vec![10, 15]);
836/// // (5 * 2), (5 + 10)
837/// ```
838///
839/// # Author
840///
841/// Haixing Hu
842pub trait FnStatefulConsumerOps<T>: FnMut(&T) + Sized {
843 /// Sequentially chain another consumer
844 ///
845 /// Returns a new consumer that executes the current operation first, then the
846 /// next operation. Consumes the current closure and returns `BoxStatefulConsumer<T>`.
847 ///
848 /// # Type Parameters
849 ///
850 /// * `C` - Type of the next consumer
851 ///
852 /// # Parameters
853 ///
854 /// * `next` - Consumer to execute after the current operation. **Note: This
855 /// parameter is passed by value and will transfer ownership.** If you need
856 /// to preserve the original consumer, clone it first (if it implements
857 /// `Clone`). Can be:
858 /// - A closure: `|x: &T|`
859 /// - A `BoxStatefulConsumer<T>`
860 /// - An `RcStatefulConsumer<T>`
861 /// - An `ArcStatefulConsumer<T>`
862 /// - Any type implementing `Consumer<T>`
863 ///
864 /// # Return Value
865 ///
866 /// Returns a combined `BoxStatefulConsumer<T>`
867 ///
868 /// # Examples
869 ///
870 /// ## Direct value passing (ownership transfer)
871 ///
872 /// ```rust
873 /// use qubit_function::{Consumer, FnStatefulConsumerOps, BoxStatefulConsumer};
874 /// use std::sync::{Arc, Mutex};
875 ///
876 /// let log = Arc::new(Mutex::new(Vec::new()));
877 /// let l1 = log.clone();
878 /// let l2 = log.clone();
879 /// let second = BoxStatefulConsumer::new(move |x: &i32| {
880 /// l2.lock().unwrap().push(*x + 10);
881 /// });
882 ///
883 /// // second is moved here
884 /// let mut chained = (move |x: &i32| {
885 /// l1.lock().unwrap().push(*x * 2);
886 /// }).and_then(second);
887 ///
888 /// chained.accept(&5);
889 /// assert_eq!(*log.lock().unwrap(), vec![10, 15]);
890 /// // second.accept(&3); // Would not compile - moved
891 /// ```
892 ///
893 /// ## Preserving original with clone
894 ///
895 /// ```rust
896 /// use qubit_function::{Consumer, FnStatefulConsumerOps, BoxStatefulConsumer};
897 /// use std::sync::{Arc, Mutex};
898 ///
899 /// let log = Arc::new(Mutex::new(Vec::new()));
900 /// let l1 = log.clone();
901 /// let l2 = log.clone();
902 /// let second = BoxStatefulConsumer::new(move |x: &i32| {
903 /// l2.lock().unwrap().push(*x + 10);
904 /// });
905 ///
906 /// // Clone to preserve original
907 /// let mut chained = (move |x: &i32| {
908 /// l1.lock().unwrap().push(*x * 2);
909 /// }).and_then(second.clone());
910 ///
911 /// chained.accept(&5);
912 /// assert_eq!(*log.lock().unwrap(), vec![10, 15]);
913 ///
914 /// // Original still usable
915 /// second.accept(&3);
916 /// assert_eq!(*log.lock().unwrap(), vec![10, 15, 13]);
917 /// ```
918 fn and_then<C>(self, next: C) -> BoxStatefulConsumer<T>
919 where
920 Self: 'static,
921 C: StatefulConsumer<T> + 'static,
922 T: 'static,
923 {
924 let mut first = self;
925 let mut second = next;
926 BoxStatefulConsumer::new(move |t| {
927 first(t);
928 second.accept(t);
929 })
930 }
931}
932
933/// Implement FnStatefulConsumerOps for all closure types
934impl<T, F> FnStatefulConsumerOps<T> for F where F: FnMut(&T) {}
935
936// ============================================================================
937// 7. BoxConditionalStatefulConsumer - Box-based Conditional Consumer
938// ============================================================================
939
940/// BoxConditionalStatefulConsumer struct
941///
942/// A conditional consumer that only executes when a predicate is satisfied.
943/// Uses `BoxStatefulConsumer` and `BoxPredicate` for single ownership semantics.
944///
945/// This type is typically created by calling `BoxStatefulConsumer::when()` and is
946/// designed to work with the `or_else()` method to create if-then-else logic.
947///
948/// # Features
949///
950/// - **Single Ownership**: Not cloneable, consumes `self` on use
951/// - **Conditional Execution**: Only consumes when predicate returns `true`
952/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
953/// - **Implements Consumer**: Can be used anywhere a `Consumer` is expected
954///
955/// # Examples
956///
957/// ## Basic Conditional Execution
958///
959/// ```rust
960/// use qubit_function::{Consumer, BoxStatefulConsumer};
961/// use std::sync::{Arc, Mutex};
962///
963/// let log = Arc::new(Mutex::new(Vec::new()));
964/// let l = log.clone();
965/// let consumer = BoxStatefulConsumer::new(move |x: &i32| {
966/// l.lock().unwrap().push(*x);
967/// });
968/// let mut conditional = consumer.when(|x: &i32| *x > 0);
969///
970/// conditional.accept(&5);
971/// assert_eq!(*log.lock().unwrap(), vec![5]); // Executed
972///
973/// conditional.accept(&-5);
974/// assert_eq!(*log.lock().unwrap(), vec![5]); // Not executed
975/// ```
976///
977/// ## With or_else Branch
978///
979/// ```rust
980/// use qubit_function::{Consumer, BoxStatefulConsumer};
981/// use std::sync::{Arc, Mutex};
982///
983/// let log = Arc::new(Mutex::new(Vec::new()));
984/// let l1 = log.clone();
985/// let l2 = log.clone();
986/// let mut consumer = BoxStatefulConsumer::new(move |x: &i32| {
987/// l1.lock().unwrap().push(*x);
988/// })
989/// .when(|x: &i32| *x > 0)
990/// .or_else(move |x: &i32| {
991/// l2.lock().unwrap().push(-*x);
992/// });
993///
994/// consumer.accept(&5);
995/// assert_eq!(*log.lock().unwrap(), vec![5]); // when branch executed
996///
997/// consumer.accept(&-5);
998/// assert_eq!(*log.lock().unwrap(), vec![5, 5]); // or_else branch executed
999/// ```
1000///
1001/// # Author
1002///
1003/// Haixing Hu
1004pub struct BoxConditionalStatefulConsumer<T> {
1005 consumer: BoxStatefulConsumer<T>,
1006 predicate: BoxPredicate<T>,
1007}
1008
1009// Use macro to generate and_then and or_else methods
1010impl_box_conditional_consumer!(
1011 BoxConditionalStatefulConsumer<T>,
1012 BoxStatefulConsumer,
1013 StatefulConsumer
1014);
1015
1016impl<T> StatefulConsumer<T> for BoxConditionalStatefulConsumer<T> {
1017 fn accept(&mut self, value: &T) {
1018 if self.predicate.test(value) {
1019 self.consumer.accept(value);
1020 }
1021 }
1022
1023 // Generates: into_box(), into_rc(), into_fn()
1024 impl_conditional_consumer_conversions!(BoxStatefulConsumer<T>, RcStatefulConsumer, FnMut);
1025}
1026
1027// Use macro to generate Debug and Display implementations
1028impl_conditional_consumer_debug_display!(BoxConditionalStatefulConsumer<T>);
1029
1030// ============================================================================
1031// 8. ArcConditionalStatefulConsumer - Arc-based Conditional Consumer
1032// ============================================================================
1033
1034/// ArcConditionalStatefulConsumer struct
1035///
1036/// A thread-safe conditional consumer that only executes when a predicate is
1037/// satisfied. Uses `ArcStatefulConsumer` and `ArcPredicate` for shared ownership across
1038/// threads.
1039///
1040/// This type is typically created by calling `ArcStatefulConsumer::when()` and is
1041/// designed to work with the `or_else()` method to create if-then-else logic.
1042///
1043/// # Features
1044///
1045/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
1046/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
1047/// - **Conditional Execution**: Only consumes when predicate returns `true`
1048/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
1049///
1050/// # Examples
1051///
1052/// ```rust
1053/// use qubit_function::{Consumer, ArcStatefulConsumer};
1054/// use std::sync::{Arc, Mutex};
1055///
1056/// let log = Arc::new(Mutex::new(Vec::new()));
1057/// let l = log.clone();
1058/// let conditional = ArcStatefulConsumer::new(move |x: &i32| {
1059/// l.lock().unwrap().push(*x);
1060/// })
1061/// .when(|x: &i32| *x > 0);
1062///
1063/// let conditional_clone = conditional.clone();
1064///
1065/// let mut value = 5;
1066/// let mut m = conditional;
1067/// m.accept(&value);
1068/// assert_eq!(*log.lock().unwrap(), vec![5]);
1069/// ```
1070///
1071/// # Author
1072///
1073/// Haixing Hu
1074pub struct ArcConditionalStatefulConsumer<T> {
1075 consumer: ArcStatefulConsumer<T>,
1076 predicate: ArcPredicate<T>,
1077}
1078
1079// Use macro to generate and_then and or_else methods
1080impl_shared_conditional_consumer!(
1081 ArcConditionalStatefulConsumer<T>,
1082 ArcStatefulConsumer,
1083 StatefulConsumer,
1084 into_arc,
1085 Send + Sync + 'static
1086);
1087
1088impl<T> StatefulConsumer<T> for ArcConditionalStatefulConsumer<T> {
1089 fn accept(&mut self, value: &T) {
1090 if self.predicate.test(value) {
1091 self.consumer.accept(value);
1092 }
1093 }
1094
1095 // Generates: into_box(), into_rc(), into_fn()
1096 impl_conditional_consumer_conversions!(BoxStatefulConsumer<T>, RcStatefulConsumer, FnMut);
1097}
1098
1099// Use macro to generate Clone implementation
1100impl_conditional_consumer_clone!(ArcConditionalStatefulConsumer<T>);
1101
1102// Use macro to generate Debug and Display implementations
1103impl_conditional_consumer_debug_display!(ArcConditionalStatefulConsumer<T>);
1104
1105// ============================================================================
1106// 9. RcConditionalStatefulConsumer - Rc-based Conditional Consumer
1107// ============================================================================
1108
1109/// RcConditionalStatefulConsumer struct
1110///
1111/// A single-threaded conditional consumer that only executes when a predicate is
1112/// satisfied. Uses `RcStatefulConsumer` and `RcPredicate` for shared ownership within a
1113/// single thread.
1114///
1115/// This type is typically created by calling `RcStatefulConsumer::when()` and is
1116/// designed to work with the `or_else()` method to create if-then-else logic.
1117///
1118/// # Features
1119///
1120/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
1121/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
1122/// - **Conditional Execution**: Only consumes when predicate returns `true`
1123/// - **No Lock Overhead**: More efficient than `ArcConditionalStatefulConsumer`
1124///
1125/// # Examples
1126///
1127/// ```rust
1128/// use qubit_function::{Consumer, RcStatefulConsumer};
1129/// use std::rc::Rc;
1130/// use std::cell::RefCell;
1131///
1132/// let log = Rc::new(RefCell::new(Vec::new()));
1133/// let l = log.clone();
1134/// let conditional = RcStatefulConsumer::new(move |x: &i32| {
1135/// l.borrow_mut().push(*x);
1136/// })
1137/// .when(|x: &i32| *x > 0);
1138///
1139/// let conditional_clone = conditional.clone();
1140///
1141/// let mut value = 5;
1142/// let mut m = conditional;
1143/// m.accept(&value);
1144/// assert_eq!(*log.borrow(), vec![5]);
1145/// ```
1146///
1147/// # Author
1148///
1149/// Haixing Hu
1150pub struct RcConditionalStatefulConsumer<T> {
1151 consumer: RcStatefulConsumer<T>,
1152 predicate: RcPredicate<T>,
1153}
1154
1155// Use macro to generate and_then and or_else methods
1156impl_shared_conditional_consumer!(
1157 RcConditionalStatefulConsumer<T>,
1158 RcStatefulConsumer,
1159 StatefulConsumer,
1160 into_rc,
1161 'static
1162);
1163
1164impl<T> StatefulConsumer<T> for RcConditionalStatefulConsumer<T> {
1165 fn accept(&mut self, value: &T) {
1166 if self.predicate.test(value) {
1167 self.consumer.accept(value);
1168 }
1169 }
1170
1171 // Generates: into_box(), into_rc(), into_fn()
1172 impl_conditional_consumer_conversions!(BoxStatefulConsumer<T>, RcStatefulConsumer, FnMut);
1173}
1174
1175// Use macro to generate Clone implementation
1176impl_conditional_consumer_clone!(RcConditionalStatefulConsumer<T>);
1177
1178// Use macro to generate Debug and Display implementations
1179impl_conditional_consumer_debug_display!(RcConditionalStatefulConsumer<T>);