qubit-function 0.8.3

Common functional programming type aliases for Rust, providing Java-style functional interfaces
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
/*******************************************************************************
 *
 *    Copyright (c) 2025 - 2026.
 *    Haixing Hu, Qubit Co. Ltd.
 *
 *    All rights reserved.
 *
 ******************************************************************************/
//! # Consumer Types
//!
//! Provides implementations of consumer interfaces for executing operations
//! that accept a single input parameter but return no result.
//!
//! It is similar to the `FnMut(&T)` trait in the standard library.
//!
//! This module provides a unified `Consumer` trait and three concrete
//! implementations based on different ownership models:
//!
//! - **`BoxStatefulConsumer<T>`**: Box-based single ownership implementation for
//!   one-time use scenarios
//! - **`ArcStatefulConsumer<T>`**: Thread-safe shared ownership implementation
//!   based on Arc<Mutex<>>
//! - **`RcStatefulConsumer<T>`**: Single-threaded shared ownership implementation
//!   based on Rc<RefCell<>>
//!
//! # Design Philosophy
//!
//! Consumer uses `FnMut(&T)` semantics, allowing modification of its own state
//! but not the input value.
//!
//! Suitable for statistics, accumulation, event handling, and other scenarios.
//!
//! # Author
//!
//! Haixing Hu
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;

use parking_lot::Mutex;

use crate::consumers::consumer_once::BoxConsumerOnce;
use crate::consumers::macros::{
    impl_box_conditional_consumer,
    impl_box_consumer_methods,
    impl_conditional_consumer_clone,
    impl_conditional_consumer_conversions,
    impl_conditional_consumer_debug_display,
    impl_consumer_clone,
    impl_consumer_common_methods,
    impl_consumer_debug_display,
    impl_shared_conditional_consumer,
    impl_shared_consumer_methods,
};
use crate::macros::{
    impl_arc_conversions,
    impl_box_conversions,
    impl_closure_trait,
    impl_rc_conversions,
};
use crate::predicates::predicate::{
    ArcPredicate,
    BoxPredicate,
    Predicate,
    RcPredicate,
};

// ============================================================================
// 1. Consumer Trait - Unified Consumer Interface
// ============================================================================

/// Consumer trait - Unified consumer interface
///
/// Defines the core behavior of all consumer types. Similar to Java's
/// `Consumer<T>` interface, executes operations that accept a value but return
/// no result (side effects only).
///
/// It is similar to the `FnMut(&T)` trait in the standard library.
///
/// Consumer can modify its own state (such as accumulation, counting), but
/// should not modify the consumed value itself.
///
/// # Automatic Implementation
///
/// - All closures implementing `FnMut(&T)`
/// - `BoxStatefulConsumer<T>`, `ArcStatefulConsumer<T>`, `RcStatefulConsumer<T>`
///
/// # Features
///
/// - **Unified Interface**: All consumer types share the same `accept` method
///   signature
/// - **Automatic Implementation**: Closures automatically implement this trait
///   with zero overhead
/// - **Type Conversion**: Easy conversion between different ownership models
/// - **Generic Programming**: Write functions that work with any consumer type
///
/// # Examples
///
/// ```rust
/// use qubit_function::{Consumer, BoxStatefulConsumer, ArcStatefulConsumer};
/// use std::sync::{Arc, Mutex};
///
/// fn apply_consumer<C: StatefulConsumer<i32>>(consumer: &mut C, value: &i32) {
///     consumer.accept(value);
/// }
///
/// // Works with any consumer type
/// let log = Arc::new(Mutex::new(Vec::new()));
/// let l = log.clone();
/// let mut box_con = BoxStatefulConsumer::new(move |x: &i32| {
///     l.lock().unwrap().push(*x);
/// });
/// apply_consumer(&mut box_con, &5);
/// assert_eq!(*log.lock().unwrap(), vec![5]);
/// ```
///
/// # Author
///
/// Haixing Hu
pub trait StatefulConsumer<T> {
    /// Execute consumption operation
    ///
    /// Performs an operation on the given reference. The operation typically
    /// reads the input value or produces side effects, but does not modify the
    /// input value itself. Can modify the consumer's own state.
    ///
    /// # Parameters
    ///
    /// * `value` - Reference to the value to be consumed
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_function::{Consumer, BoxStatefulConsumer};
    ///
    /// let mut consumer = BoxStatefulConsumer::new(|x: &i32| println!("{}", x));
    /// let value = 5;
    /// consumer.accept(&value);
    /// ```
    fn accept(&mut self, value: &T);

    /// Convert to BoxStatefulConsumer
    ///
    /// **⚠️ Consumes `self`**: The original consumer will be unavailable after
    /// calling this method.
    ///
    /// Converts the current consumer to `BoxStatefulConsumer<T>`.
    ///
    /// # Ownership
    ///
    /// This method **consumes** the consumer (takes ownership of `self`).
    /// After calling this method, the original consumer is no longer available.
    ///
    /// **Tip**: For cloneable consumers ([`ArcStatefulConsumer`], [`RcStatefulConsumer`]),
    /// if you need to preserve the original object, you can call `.clone()`
    /// first.
    ///
    /// # Return Value
    ///
    /// Returns the wrapped `BoxStatefulConsumer<T>`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_function::Consumer;
    /// use std::sync::{Arc, Mutex};
    ///
    /// let log = Arc::new(Mutex::new(Vec::new()));
    /// let l = log.clone();
    /// let closure = move |x: &i32| {
    ///     l.lock().unwrap().push(*x);
    /// };
    /// let mut box_consumer = closure.into_box();
    /// box_consumer.accept(&5);
    /// assert_eq!(*log.lock().unwrap(), vec![5]);
    /// ```
    fn into_box(self) -> BoxStatefulConsumer<T>
    where
        Self: Sized + 'static,
    {
        let mut consumer = self;
        BoxStatefulConsumer::new(move |t| consumer.accept(t))
    }

    /// Convert to RcStatefulConsumer
    ///
    /// **⚠️ Consumes `self`**: The original consumer will be unavailable after
    /// calling this method.
    ///
    /// # Return Value
    ///
    /// Returns the wrapped `RcStatefulConsumer<T>`
    fn into_rc(self) -> RcStatefulConsumer<T>
    where
        Self: Sized + 'static,
    {
        let mut consumer = self;
        RcStatefulConsumer::new(move |t| consumer.accept(t))
    }

    /// Convert to ArcStatefulConsumer
    ///
    /// **⚠️ Consumes `self`**: The original consumer will be unavailable after
    /// calling this method.
    ///
    /// # Return Value
    ///
    /// Returns the wrapped `ArcStatefulConsumer<T>`
    fn into_arc(self) -> ArcStatefulConsumer<T>
    where
        Self: Sized + Send + 'static,
    {
        let mut consumer = self;
        ArcStatefulConsumer::new(move |t| consumer.accept(t))
    }

    /// Convert to closure
    ///
    /// **⚠️ Consumes `self`**: The original consumer will be unavailable after
    /// calling this method.
    ///
    /// Converts the consumer to a closure that can be used directly in standard
    /// library functions requiring `FnMut`.
    ///
    /// # Return Value
    ///
    /// Returns a closure implementing `FnMut(&T)`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_function::{Consumer, BoxStatefulConsumer};
    /// use std::sync::{Arc, Mutex};
    ///
    /// let log = Arc::new(Mutex::new(Vec::new()));
    /// let l = log.clone();
    /// let consumer = BoxStatefulConsumer::new(move |x: &i32| {
    ///     l.lock().unwrap().push(*x);
    /// });
    /// let mut func = consumer.into_fn();
    /// func(&5);
    /// assert_eq!(*log.lock().unwrap(), vec![5]);
    /// ```
    fn into_fn(self) -> impl FnMut(&T)
    where
        Self: Sized + 'static,
    {
        let mut consumer = self;
        move |t| consumer.accept(t)
    }

    /// Convert to ConsumerOnce
    ///
    /// **⚠️ Consumes `self`**: The original consumer will be unavailable after calling this method.
    ///
    /// Converts a reusable stateful consumer to a one-time consumer that consumes itself on use.
    /// This enables passing `StatefulConsumer` to functions that require `ConsumerOnce`.
    ///
    /// # Returns
    ///
    /// Returns a `BoxConsumerOnce<T>`
    ///
    /// # Examples
    ///
    /// ```rust
    ///
    /// fn takes_once<C: ConsumerOnce<i32>>(consumer: C, value: &i32) {
    ///     consumer.accept(value);
    /// }
    ///
    /// let consumer = BoxStatefulConsumer::new(|x: &i32| println!("{}", x));
    /// takes_once(consumer.into_once(), &5);
    /// ```
    fn into_once(self) -> BoxConsumerOnce<T>
    where
        Self: Sized + 'static,
    {
        BoxConsumerOnce::new(move |t| {
            let mut consumer = self;
            consumer.accept(t);
        })
    }

    /// Convert to BoxStatefulConsumer
    ///
    /// **⚠️ Requires Clone**: The original consumer must implement Clone.
    ///
    /// Converts the current consumer to `BoxStatefulConsumer<T>` by cloning it first.
    ///
    /// # Ownership
    ///
    /// This method does **not consume** the consumer. It clones the consumer and
    /// then converts the clone to `BoxStatefulConsumer<T>`. The original consumer remains
    /// available after calling this method.
    ///
    /// # Return Value
    ///
    /// Returns the wrapped `BoxStatefulConsumer<T>` from the clone
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_function::{Consumer, ArcStatefulConsumer};
    /// use std::sync::{Arc, Mutex};
    ///
    /// let log = Arc::new(Mutex::new(Vec::new()));
    /// let l = log.clone();
    /// let consumer = ArcStatefulConsumer::new(move |x: &i32| {
    ///     l.lock().unwrap().push(*x);
    /// });
    /// let mut box_consumer = consumer.to_box();
    /// box_consumer.accept(&5);
    /// assert_eq!(*log.lock().unwrap(), vec![5]);
    /// // Original consumer still usable
    /// consumer.accept(&3);
    /// assert_eq!(*log.lock().unwrap(), vec![5, 3]);
    /// ```
    fn to_box(&self) -> BoxStatefulConsumer<T>
    where
        Self: Sized + Clone + 'static,
    {
        self.clone().into_box()
    }

    /// Convert to RcStatefulConsumer
    ///
    /// **⚠️ Requires Clone**: The original consumer must implement Clone.
    ///
    /// Converts the current consumer to `RcStatefulConsumer<T>` by cloning it first.
    ///
    /// # Ownership
    ///
    /// This method does **not consume** the consumer. It clones the consumer and
    /// then converts the clone to `RcStatefulConsumer<T>`. The original consumer remains
    /// available after calling this method.
    ///
    /// # Return Value
    ///
    /// Returns the wrapped `RcStatefulConsumer<T>` from the clone
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_function::{Consumer, ArcStatefulConsumer};
    /// use std::sync::{Arc, Mutex};
    ///
    /// let log = Arc::new(Mutex::new(Vec::new()));
    /// let l = log.clone();
    /// let consumer = ArcStatefulConsumer::new(move |x: &i32| {
    ///     l.lock().unwrap().push(*x);
    /// });
    /// let mut rc_consumer = consumer.to_rc();
    /// rc_consumer.accept(&5);
    /// assert_eq!(*log.lock().unwrap(), vec![5]);
    /// // Original consumer still usable
    /// consumer.accept(&3);
    /// assert_eq!(*log.lock().unwrap(), vec![5, 3]);
    /// ```
    fn to_rc(&self) -> RcStatefulConsumer<T>
    where
        Self: Sized + Clone + 'static,
    {
        self.clone().into_rc()
    }

    /// Convert to ArcStatefulConsumer
    ///
    /// **⚠️ Requires Clone + Send**: The original consumer must implement
    /// Clone + Send.
    ///
    /// Converts the current consumer to `ArcStatefulConsumer<T>` by cloning it first.
    ///
    /// # Ownership
    ///
    /// This method does **not consume** the consumer. It clones the consumer and
    /// then converts the clone to `ArcStatefulConsumer<T>`. The original consumer remains
    /// available after calling this method.
    ///
    /// # Return Value
    ///
    /// Returns the wrapped `ArcStatefulConsumer<T>` from the clone
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_function::{Consumer, RcStatefulConsumer};
    /// use std::rc::Rc;
    /// use std::cell::RefCell;
    ///
    /// let log = Rc::new(RefCell::new(Vec::new()));
    /// let l = log.clone();
    /// let consumer = RcStatefulConsumer::new(move |x: &i32| {
    ///     l.borrow_mut().push(*x);
    /// });
    /// let mut arc_consumer = consumer.to_arc();
    /// arc_consumer.accept(&5);
    /// assert_eq!(*log.borrow(), vec![5]);
    /// // Original consumer still usable
    /// consumer.accept(&3);
    /// assert_eq!(*log.borrow(), vec![5, 3]);
    /// ```
    fn to_arc(&self) -> ArcStatefulConsumer<T>
    where
        Self: Sized + Clone + Send + 'static,
    {
        self.clone().into_arc()
    }

    /// Convert to closure
    ///
    /// **⚠️ Requires Clone**: The original consumer must implement Clone.
    ///
    /// Converts the consumer to a closure that can be used directly in standard
    /// library functions requiring `FnMut`.
    ///
    /// # Ownership
    ///
    /// This method does **not consume** the consumer. It clones the consumer and
    /// then converts the clone to a closure. The original consumer remains
    /// available after calling this method.
    ///
    /// # Return Value
    ///
    /// Returns a closure implementing `FnMut(&T)` from the clone
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_function::{Consumer, BoxStatefulConsumer};
    /// use std::sync::{Arc, Mutex};
    ///
    /// let log = Arc::new(Mutex::new(Vec::new()));
    /// let l = log.clone();
    /// let consumer = BoxStatefulConsumer::new(move |x: &i32| {
    ///     l.lock().unwrap().push(*x);
    /// });
    /// let mut func = consumer.to_fn();
    /// func(&5);
    /// assert_eq!(*log.lock().unwrap(), vec![5]);
    /// // Original consumer still usable
    /// consumer.accept(&3);
    /// assert_eq!(*log.lock().unwrap(), vec![5, 3]);
    /// ```
    fn to_fn(&self) -> impl FnMut(&T)
    where
        Self: Sized + Clone + 'static,
    {
        self.clone().into_fn()
    }

    /// Convert to ConsumerOnce without consuming self
    ///
    /// **⚠️ Requires Clone**: This method requires `Self` to implement `Clone`.
    /// Clones the current consumer and converts the clone to a one-time consumer.
    ///
    /// # Returns
    ///
    /// Returns a `BoxConsumerOnce<T>`
    ///
    /// # Examples
    ///
    /// ```rust
    ///
    /// fn takes_once<C: ConsumerOnce<i32>>(consumer: C, value: &i32) {
    ///     consumer.accept(value);
    /// }
    ///
    /// let consumer = BoxStatefulConsumer::new(|x: &i32| println!("{}", x));
    /// takes_once(consumer.to_once(), &5);
    /// ```
    fn to_once(&self) -> BoxConsumerOnce<T>
    where
        Self: Clone + 'static,
    {
        self.clone().into_once()
    }
}

// ============================================================================
// 2. BoxStatefulConsumer - Single Ownership Implementation
// ============================================================================

/// BoxStatefulConsumer struct
///
/// Consumer implementation based on `Box<dyn FnMut(&T)>` for single ownership
/// scenarios. When sharing is not needed, this is the simplest and most
/// efficient consumer type.
///
/// # Features
///
/// - **Single Ownership**: Not cloneable, transfers ownership when used
/// - **Zero Overhead**: No reference counting or lock overhead
/// - **Mutable State**: Can modify captured environment through `FnMut`
/// - **Builder Pattern**: Method chaining naturally consumes `self`
///
/// # Use Cases
///
/// Choose `BoxStatefulConsumer` when:
/// - Consumer is used only once or in a linear flow
/// - Building pipelines where ownership flows naturally
/// - No need to share consumers across contexts
/// - Performance critical and cannot accept sharing overhead
///
/// # Performance
///
/// `BoxStatefulConsumer` has the best performance among the three consumer types:
/// - No reference counting overhead
/// - No lock acquisition or runtime borrowing checks
/// - Direct function calls through vtable
/// - Minimal memory footprint (single pointer)
///
/// # Examples
///
/// ```rust
/// use qubit_function::{Consumer, BoxStatefulConsumer};
/// use std::sync::{Arc, Mutex};
///
/// let log = Arc::new(Mutex::new(Vec::new()));
/// let l = log.clone();
/// let mut consumer = BoxStatefulConsumer::new(move |x: &i32| {
///     l.lock().unwrap().push(*x);
/// });
/// consumer.accept(&5);
/// assert_eq!(*log.lock().unwrap(), vec![5]);
/// ```
///
/// # Author
///
/// Haixing Hu
pub struct BoxStatefulConsumer<T> {
    function: Box<dyn FnMut(&T)>,
    name: Option<String>,
}

impl<T> BoxStatefulConsumer<T> {
    // Generates: new(), new_with_name(), name(), set_name(), noop()
    impl_consumer_common_methods!(BoxStatefulConsumer<T>, (FnMut(&T) + 'static), |f| Box::new(
        f
    ));

    // Generates: when() and and_then() methods that consume self
    impl_box_consumer_methods!(
        BoxStatefulConsumer<T>,
        BoxConditionalStatefulConsumer,
        StatefulConsumer
    );
}

impl<T> StatefulConsumer<T> for BoxStatefulConsumer<T> {
    fn accept(&mut self, value: &T) {
        (self.function)(value)
    }

    // Generates: into_box(), into_rc(), into_fn(), into_once()
    impl_box_conversions!(
        BoxStatefulConsumer<T>,
        RcStatefulConsumer,
        FnMut(&T),
        BoxConsumerOnce
    );
}

// Use macro to generate Debug and Display implementations
impl_consumer_debug_display!(BoxStatefulConsumer<T>);

// ============================================================================
// 3. RcStatefulConsumer - Single-Threaded Shared Ownership Implementation
// ============================================================================

/// RcStatefulConsumer struct
///
/// Consumer implementation based on `Rc<RefCell<dyn FnMut(&T)>>` for
/// single-threaded shared ownership scenarios. This consumer provides the
/// benefits of shared ownership without the overhead of thread safety.
///
/// # Features
///
/// - **Shared Ownership**: Cloneable through `Rc`, allowing multiple owners
/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
/// - **Interior Mutability**: Uses `RefCell` for runtime borrowing checks
/// - **No Lock Overhead**: More efficient than `ArcStatefulConsumer` for single-threaded
///   use
/// - **Non-Consuming API**: `and_then` borrows `&self`, original object remains
///   usable
///
/// # Use Cases
///
/// Choose `RcStatefulConsumer` when:
/// - Need to share consumers within a single thread
/// - Thread safety is not needed
/// - Performance is important (avoid lock overhead)
/// - UI event handling in single-threaded frameworks
/// - Building complex single-threaded state machines
///
/// # Performance Considerations
///
/// `RcStatefulConsumer` performs better than `ArcStatefulConsumer` in single-threaded scenarios:
/// - **Non-Atomic Counting**: clone/drop is cheaper than `Arc`
/// - **No Lock Overhead**: `RefCell` uses runtime checks, no locks
/// - **Better Cache Locality**: No atomic operations means better CPU cache
///   behavior
///
/// But still has slight overhead compared to `BoxStatefulConsumer`:
/// - **Reference Counting**: Non-atomic but still exists
/// - **Runtime Borrowing Checks**: `RefCell` checks at runtime
///
/// # Safety
///
/// `RcStatefulConsumer` is not thread-safe and does not implement `Send` or `Sync`.
/// Attempting to send it to another thread will result in a compilation error.
/// For thread-safe sharing, use `ArcStatefulConsumer` instead.
///
/// # Examples
///
/// ```rust
/// use qubit_function::{Consumer, RcStatefulConsumer};
/// use std::rc::Rc;
/// use std::cell::RefCell;
///
/// let log = Rc::new(RefCell::new(Vec::new()));
/// let l = log.clone();
/// let mut consumer = RcStatefulConsumer::new(move |x: &i32| {
///     l.borrow_mut().push(*x * 2);
/// });
/// let mut clone = consumer.clone();
///
/// consumer.accept(&5);
/// assert_eq!(*log.borrow(), vec![10]);
/// ```
///
/// # Author
///
/// Haixing Hu
pub struct RcStatefulConsumer<T> {
    function: Rc<RefCell<dyn FnMut(&T)>>,
    name: Option<String>,
}

impl<T> RcStatefulConsumer<T> {
    // Generates: new(), new_with_name(), name(), set_name(), noop()
    impl_consumer_common_methods!(RcStatefulConsumer<T>, (FnMut(&T) + 'static), |f| Rc::new(
        RefCell::new(f)
    ));

    // Generates: when() and and_then() methods that borrow &self (Rc can clone)
    impl_shared_consumer_methods!(
        RcStatefulConsumer<T>,
        RcConditionalStatefulConsumer,
        into_rc,
        StatefulConsumer,
        'static
    );
}

impl<T> StatefulConsumer<T> for RcStatefulConsumer<T> {
    fn accept(&mut self, value: &T) {
        (self.function.borrow_mut())(value)
    }

    // Use macro to implement conversion methods
    impl_rc_conversions!(
        RcStatefulConsumer<T>,
        BoxStatefulConsumer,
        BoxConsumerOnce,
        FnMut(t: &T)
    );
}

// Use macro to generate Clone implementation
impl_consumer_clone!(RcStatefulConsumer<T>);

// Use macro to generate Debug and Display implementations
impl_consumer_debug_display!(RcStatefulConsumer<T>);

// ============================================================================
// 4. ArcStatefulConsumer - Thread-Safe Shared Ownership Implementation
// ============================================================================

/// ArcStatefulConsumer struct
///
/// Consumer implementation based on `Arc<Mutex<dyn FnMut(&T) + Send>>` for
/// thread-safe shared ownership scenarios. This consumer can be safely cloned
/// and shared across multiple threads.
///
/// # Features
///
/// - **Shared Ownership**: Cloneable through `Arc`, allowing multiple owners
/// - **Thread Safety**: Implements `Send + Sync`, safe for concurrent use
/// - **Interior Mutability**: Uses `Mutex` for safe mutable access
/// - **Non-Consuming API**: `and_then` borrows `&self`, original object remains
///   usable
/// - **Cross-Thread Sharing**: Can be sent to other threads and used
///
/// # Use Cases
///
/// Choose `ArcStatefulConsumer` when:
/// - Need to share consumers across multiple threads
/// - Concurrent task processing (e.g., thread pools)
/// - Using the same consumer in multiple places simultaneously
/// - Need thread safety (Send + Sync)
///
/// # Performance Considerations
///
/// `ArcStatefulConsumer` has some performance overhead compared to `BoxStatefulConsumer`:
/// - **Reference Counting**: Atomic operations on clone/drop
/// - **Mutex Locking**: Each `accept` call requires lock acquisition
/// - **Lock Contention**: High concurrency may cause contention
///
/// These overheads are necessary for safe concurrent access. If thread safety
/// is not needed, consider using `RcStatefulConsumer` for less single-threaded sharing
/// overhead.
///
/// # Examples
///
/// ```rust
/// use qubit_function::{Consumer, ArcStatefulConsumer};
/// use std::sync::{Arc, Mutex};
///
/// let log = Arc::new(Mutex::new(Vec::new()));
/// let l = log.clone();
/// let mut consumer = ArcStatefulConsumer::new(move |x: &i32| {
///     l.lock().unwrap().push(*x * 2);
/// });
/// let mut clone = consumer.clone();
///
/// consumer.accept(&5);
/// assert_eq!(*log.lock().unwrap(), vec![10]);
/// ```
///
/// # Author
///
/// Haixing Hu
pub struct ArcStatefulConsumer<T> {
    function: Arc<Mutex<dyn FnMut(&T) + Send>>,
    name: Option<String>,
}

impl<T> ArcStatefulConsumer<T> {
    // Generates: new(), new_with_name(), name(), set_name(), noop()
    impl_consumer_common_methods!(ArcStatefulConsumer<T>, (FnMut(&T) + Send + 'static), |f| {
        Arc::new(Mutex::new(f))
    });

    // Generates: when() and and_then() methods that borrow &self (Arc can clone)
    impl_shared_consumer_methods!(
        ArcStatefulConsumer<T>,
        ArcConditionalStatefulConsumer,
        into_arc,
        StatefulConsumer,
        Send + Sync + 'static
    );
}

impl<T> StatefulConsumer<T> for ArcStatefulConsumer<T> {
    fn accept(&mut self, value: &T) {
        (self.function.lock())(value)
    }

    // Use macro to implement conversion methods
    impl_arc_conversions!(
        ArcStatefulConsumer<T>,
        BoxStatefulConsumer,
        RcStatefulConsumer,
        BoxConsumerOnce,
        FnMut(t: &T)
    );
}

// Use macro to generate Clone implementation
impl_consumer_clone!(ArcStatefulConsumer<T>);

// Use macro to generate Debug and Display implementations
impl_consumer_debug_display!(ArcStatefulConsumer<T>);

// ============================================================================
// 5. Implement Consumer trait for closures
// ============================================================================

// Implement Consumer for all FnMut(&T)
impl_closure_trait!(
    StatefulConsumer<T>,
    accept,
    BoxConsumerOnce,
    FnMut(value: &T)
);

// ============================================================================
// 6. Extension methods for closures
// ============================================================================

/// Extension trait providing consumer composition methods for closures
///
/// Provides `and_then` and other composition methods for all closures
/// implementing `FnMut(&T)`, allowing direct method chaining on closures
/// without explicit wrapper types.
///
/// # Design Philosophy
///
/// This trait allows closures to be naturally composed using method syntax,
/// similar to iterator combinators. Composition methods consume the closure and
/// return `BoxStatefulConsumer<T>`, which can continue chaining.
///
/// # Features
///
/// - **Natural Syntax**: Direct method chaining on closures
/// - **Returns BoxStatefulConsumer**: Composition results in `BoxStatefulConsumer<T>`, can
///   continue chaining
/// - **Zero Cost**: No overhead when composing closures
/// - **Automatic Implementation**: All `FnMut(&T)` closures automatically get
///   these methods
///
/// # Examples
///
/// ```rust
/// use qubit_function::{Consumer, FnStatefulConsumerOps};
/// use std::sync::{Arc, Mutex};
///
/// let log = Arc::new(Mutex::new(Vec::new()));
/// let l1 = log.clone();
/// let l2 = log.clone();
/// let mut chained = (move |x: &i32| {
///     l1.lock().unwrap().push(*x * 2);
/// }).and_then(move |x: &i32| {
///     l2.lock().unwrap().push(*x + 10);
/// });
/// chained.accept(&5);
/// assert_eq!(*log.lock().unwrap(), vec![10, 15]);
/// // (5 * 2), (5 + 10)
/// ```
///
/// # Author
///
/// Haixing Hu
pub trait FnStatefulConsumerOps<T>: FnMut(&T) + Sized {
    /// Sequentially chain another consumer
    ///
    /// Returns a new consumer that executes the current operation first, then the
    /// next operation. Consumes the current closure and returns `BoxStatefulConsumer<T>`.
    ///
    /// # Type Parameters
    ///
    /// * `C` - Type of the next consumer
    ///
    /// # Parameters
    ///
    /// * `next` - Consumer to execute after the current operation. **Note: This
    ///   parameter is passed by value and will transfer ownership.** If you need
    ///   to preserve the original consumer, clone it first (if it implements
    ///   `Clone`). Can be:
    ///   - A closure: `|x: &T|`
    ///   - A `BoxStatefulConsumer<T>`
    ///   - An `RcStatefulConsumer<T>`
    ///   - An `ArcStatefulConsumer<T>`
    ///   - Any type implementing `Consumer<T>`
    ///
    /// # Return Value
    ///
    /// Returns a combined `BoxStatefulConsumer<T>`
    ///
    /// # Examples
    ///
    /// ## Direct value passing (ownership transfer)
    ///
    /// ```rust
    /// use qubit_function::{Consumer, FnStatefulConsumerOps, BoxStatefulConsumer};
    /// use std::sync::{Arc, Mutex};
    ///
    /// let log = Arc::new(Mutex::new(Vec::new()));
    /// let l1 = log.clone();
    /// let l2 = log.clone();
    /// let second = BoxStatefulConsumer::new(move |x: &i32| {
    ///     l2.lock().unwrap().push(*x + 10);
    /// });
    ///
    /// // second is moved here
    /// let mut chained = (move |x: &i32| {
    ///     l1.lock().unwrap().push(*x * 2);
    /// }).and_then(second);
    ///
    /// chained.accept(&5);
    /// assert_eq!(*log.lock().unwrap(), vec![10, 15]);
    /// // second.accept(&3); // Would not compile - moved
    /// ```
    ///
    /// ## Preserving original with clone
    ///
    /// ```rust
    /// use qubit_function::{Consumer, FnStatefulConsumerOps, BoxStatefulConsumer};
    /// use std::sync::{Arc, Mutex};
    ///
    /// let log = Arc::new(Mutex::new(Vec::new()));
    /// let l1 = log.clone();
    /// let l2 = log.clone();
    /// let second = BoxStatefulConsumer::new(move |x: &i32| {
    ///     l2.lock().unwrap().push(*x + 10);
    /// });
    ///
    /// // Clone to preserve original
    /// let mut chained = (move |x: &i32| {
    ///     l1.lock().unwrap().push(*x * 2);
    /// }).and_then(second.clone());
    ///
    /// chained.accept(&5);
    /// assert_eq!(*log.lock().unwrap(), vec![10, 15]);
    ///
    /// // Original still usable
    /// second.accept(&3);
    /// assert_eq!(*log.lock().unwrap(), vec![10, 15, 13]);
    /// ```
    fn and_then<C>(self, next: C) -> BoxStatefulConsumer<T>
    where
        Self: 'static,
        C: StatefulConsumer<T> + 'static,
        T: 'static,
    {
        let mut first = self;
        let mut second = next;
        BoxStatefulConsumer::new(move |t| {
            first(t);
            second.accept(t);
        })
    }
}

/// Implement FnStatefulConsumerOps for all closure types
impl<T, F> FnStatefulConsumerOps<T> for F where F: FnMut(&T) {}

// ============================================================================
// 7. BoxConditionalStatefulConsumer - Box-based Conditional Consumer
// ============================================================================

/// BoxConditionalStatefulConsumer struct
///
/// A conditional consumer that only executes when a predicate is satisfied.
/// Uses `BoxStatefulConsumer` and `BoxPredicate` for single ownership semantics.
///
/// This type is typically created by calling `BoxStatefulConsumer::when()` and is
/// designed to work with the `or_else()` method to create if-then-else logic.
///
/// # Features
///
/// - **Single Ownership**: Not cloneable, consumes `self` on use
/// - **Conditional Execution**: Only consumes when predicate returns `true`
/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
/// - **Implements Consumer**: Can be used anywhere a `Consumer` is expected
///
/// # Examples
///
/// ## Basic Conditional Execution
///
/// ```rust
/// use qubit_function::{Consumer, BoxStatefulConsumer};
/// use std::sync::{Arc, Mutex};
///
/// let log = Arc::new(Mutex::new(Vec::new()));
/// let l = log.clone();
/// let consumer = BoxStatefulConsumer::new(move |x: &i32| {
///     l.lock().unwrap().push(*x);
/// });
/// let mut conditional = consumer.when(|x: &i32| *x > 0);
///
/// conditional.accept(&5);
/// assert_eq!(*log.lock().unwrap(), vec![5]); // Executed
///
/// conditional.accept(&-5);
/// assert_eq!(*log.lock().unwrap(), vec![5]); // Not executed
/// ```
///
/// ## With or_else Branch
///
/// ```rust
/// use qubit_function::{Consumer, BoxStatefulConsumer};
/// use std::sync::{Arc, Mutex};
///
/// let log = Arc::new(Mutex::new(Vec::new()));
/// let l1 = log.clone();
/// let l2 = log.clone();
/// let mut consumer = BoxStatefulConsumer::new(move |x: &i32| {
///     l1.lock().unwrap().push(*x);
/// })
/// .when(|x: &i32| *x > 0)
/// .or_else(move |x: &i32| {
///     l2.lock().unwrap().push(-*x);
/// });
///
/// consumer.accept(&5);
/// assert_eq!(*log.lock().unwrap(), vec![5]); // when branch executed
///
/// consumer.accept(&-5);
/// assert_eq!(*log.lock().unwrap(), vec![5, 5]); // or_else branch executed
/// ```
///
/// # Author
///
/// Haixing Hu
pub struct BoxConditionalStatefulConsumer<T> {
    consumer: BoxStatefulConsumer<T>,
    predicate: BoxPredicate<T>,
}

// Use macro to generate and_then and or_else methods
impl_box_conditional_consumer!(
    BoxConditionalStatefulConsumer<T>,
    BoxStatefulConsumer,
    StatefulConsumer
);

impl<T> StatefulConsumer<T> for BoxConditionalStatefulConsumer<T> {
    fn accept(&mut self, value: &T) {
        if self.predicate.test(value) {
            self.consumer.accept(value);
        }
    }

    // Generates: into_box(), into_rc(), into_fn()
    impl_conditional_consumer_conversions!(BoxStatefulConsumer<T>, RcStatefulConsumer, FnMut);
}

// Use macro to generate Debug and Display implementations
impl_conditional_consumer_debug_display!(BoxConditionalStatefulConsumer<T>);

// ============================================================================
// 8. ArcConditionalStatefulConsumer - Arc-based Conditional Consumer
// ============================================================================

/// ArcConditionalStatefulConsumer struct
///
/// A thread-safe conditional consumer that only executes when a predicate is
/// satisfied. Uses `ArcStatefulConsumer` and `ArcPredicate` for shared ownership across
/// threads.
///
/// This type is typically created by calling `ArcStatefulConsumer::when()` and is
/// designed to work with the `or_else()` method to create if-then-else logic.
///
/// # Features
///
/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
/// - **Conditional Execution**: Only consumes when predicate returns `true`
/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
///
/// # Examples
///
/// ```rust
/// use qubit_function::{Consumer, ArcStatefulConsumer};
/// use std::sync::{Arc, Mutex};
///
/// let log = Arc::new(Mutex::new(Vec::new()));
/// let l = log.clone();
/// let conditional = ArcStatefulConsumer::new(move |x: &i32| {
///     l.lock().unwrap().push(*x);
/// })
/// .when(|x: &i32| *x > 0);
///
/// let conditional_clone = conditional.clone();
///
/// let mut value = 5;
/// let mut m = conditional;
/// m.accept(&value);
/// assert_eq!(*log.lock().unwrap(), vec![5]);
/// ```
///
/// # Author
///
/// Haixing Hu
pub struct ArcConditionalStatefulConsumer<T> {
    consumer: ArcStatefulConsumer<T>,
    predicate: ArcPredicate<T>,
}

// Use macro to generate and_then and or_else methods
impl_shared_conditional_consumer!(
    ArcConditionalStatefulConsumer<T>,
    ArcStatefulConsumer,
    StatefulConsumer,
    into_arc,
    Send + Sync + 'static
);

impl<T> StatefulConsumer<T> for ArcConditionalStatefulConsumer<T> {
    fn accept(&mut self, value: &T) {
        if self.predicate.test(value) {
            self.consumer.accept(value);
        }
    }

    // Generates: into_box(), into_rc(), into_fn()
    impl_conditional_consumer_conversions!(BoxStatefulConsumer<T>, RcStatefulConsumer, FnMut);
}

// Use macro to generate Clone implementation
impl_conditional_consumer_clone!(ArcConditionalStatefulConsumer<T>);

// Use macro to generate Debug and Display implementations
impl_conditional_consumer_debug_display!(ArcConditionalStatefulConsumer<T>);

// ============================================================================
// 9. RcConditionalStatefulConsumer - Rc-based Conditional Consumer
// ============================================================================

/// RcConditionalStatefulConsumer struct
///
/// A single-threaded conditional consumer that only executes when a predicate is
/// satisfied. Uses `RcStatefulConsumer` and `RcPredicate` for shared ownership within a
/// single thread.
///
/// This type is typically created by calling `RcStatefulConsumer::when()` and is
/// designed to work with the `or_else()` method to create if-then-else logic.
///
/// # Features
///
/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
/// - **Conditional Execution**: Only consumes when predicate returns `true`
/// - **No Lock Overhead**: More efficient than `ArcConditionalStatefulConsumer`
///
/// # Examples
///
/// ```rust
/// use qubit_function::{Consumer, RcStatefulConsumer};
/// use std::rc::Rc;
/// use std::cell::RefCell;
///
/// let log = Rc::new(RefCell::new(Vec::new()));
/// let l = log.clone();
/// let conditional = RcStatefulConsumer::new(move |x: &i32| {
///     l.borrow_mut().push(*x);
/// })
/// .when(|x: &i32| *x > 0);
///
/// let conditional_clone = conditional.clone();
///
/// let mut value = 5;
/// let mut m = conditional;
/// m.accept(&value);
/// assert_eq!(*log.borrow(), vec![5]);
/// ```
///
/// # Author
///
/// Haixing Hu
pub struct RcConditionalStatefulConsumer<T> {
    consumer: RcStatefulConsumer<T>,
    predicate: RcPredicate<T>,
}

// Use macro to generate and_then and or_else methods
impl_shared_conditional_consumer!(
    RcConditionalStatefulConsumer<T>,
    RcStatefulConsumer,
    StatefulConsumer,
    into_rc,
    'static
);

impl<T> StatefulConsumer<T> for RcConditionalStatefulConsumer<T> {
    fn accept(&mut self, value: &T) {
        if self.predicate.test(value) {
            self.consumer.accept(value);
        }
    }

    // Generates: into_box(), into_rc(), into_fn()
    impl_conditional_consumer_conversions!(BoxStatefulConsumer<T>, RcStatefulConsumer, FnMut);
}

// Use macro to generate Clone implementation
impl_conditional_consumer_clone!(RcConditionalStatefulConsumer<T>);

// Use macro to generate Debug and Display implementations
impl_conditional_consumer_debug_display!(RcConditionalStatefulConsumer<T>);