prism3_function/consumers/
stateful_consumer.rs

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