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