qubit_function/consumers/stateful_consumer/rc_stateful_consumer.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026.
4 * Haixing Hu, Qubit Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! Defines the `RcStatefulConsumer` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// 3. RcStatefulConsumer - Single-Threaded Shared Ownership Implementation
17// ============================================================================
18
19/// RcStatefulConsumer struct
20///
21/// Consumer implementation based on `Rc<RefCell<dyn FnMut(&T)>>` for
22/// single-threaded shared ownership scenarios. This consumer provides the
23/// benefits of shared ownership without the overhead of thread safety.
24///
25/// # Features
26///
27/// - **Shared Ownership**: Cloneable through `Rc`, allowing multiple owners
28/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
29/// - **Interior Mutability**: Uses `RefCell` for runtime borrowing checks
30/// - **No Lock Overhead**: More efficient than `ArcStatefulConsumer` for single-threaded
31/// use
32/// - **Non-Consuming API**: `and_then` borrows `&self`, original object remains
33/// usable
34///
35/// # Use Cases
36///
37/// Choose `RcStatefulConsumer` when:
38/// - Need to share consumers within a single thread
39/// - Thread safety is not needed
40/// - Performance is important (avoid lock overhead)
41/// - UI event handling in single-threaded frameworks
42/// - Building complex single-threaded state machines
43///
44/// # Performance Considerations
45///
46/// `RcStatefulConsumer` performs better than `ArcStatefulConsumer` in single-threaded scenarios:
47/// - **Non-Atomic Counting**: clone/drop is cheaper than `Arc`
48/// - **No Lock Overhead**: `RefCell` uses runtime checks, no locks
49/// - **Better Cache Locality**: No atomic operations means better CPU cache
50/// behavior
51///
52/// But still has slight overhead compared to `BoxStatefulConsumer`:
53/// - **Reference Counting**: Non-atomic but still exists
54/// - **Runtime Borrowing Checks**: `RefCell` checks at runtime
55///
56/// # Safety
57///
58/// `RcStatefulConsumer` is not thread-safe and does not implement `Send` or `Sync`.
59/// Attempting to send it to another thread will result in a compilation error.
60/// For thread-safe sharing, use `ArcStatefulConsumer` instead.
61///
62/// # Examples
63///
64/// ```rust
65/// use qubit_function::{Consumer, StatefulConsumer, RcStatefulConsumer};
66/// use std::rc::Rc;
67/// use std::cell::RefCell;
68///
69/// let log = Rc::new(RefCell::new(Vec::new()));
70/// let l = log.clone();
71/// let mut consumer = RcStatefulConsumer::new(move |x: &i32| {
72/// l.borrow_mut().push(*x * 2);
73/// });
74/// let mut clone = consumer.clone();
75///
76/// consumer.accept(&5);
77/// assert_eq!(*log.borrow(), vec![10]);
78/// ```
79///
80/// # Author
81///
82/// Haixing Hu
83pub struct RcStatefulConsumer<T> {
84 pub(super) function: Rc<RefCell<dyn FnMut(&T)>>,
85 pub(super) name: Option<String>,
86}
87
88impl<T> RcStatefulConsumer<T> {
89 // Generates: new(), new_with_name(), name(), set_name(), noop()
90 impl_consumer_common_methods!(RcStatefulConsumer<T>, (FnMut(&T) + 'static), |f| Rc::new(
91 RefCell::new(f)
92 ));
93
94 // Generates: when() and and_then() methods that borrow &self (Rc can clone)
95 impl_shared_consumer_methods!(
96 RcStatefulConsumer<T>,
97 RcConditionalStatefulConsumer,
98 into_rc,
99 StatefulConsumer,
100 'static
101 );
102}
103
104impl<T> StatefulConsumer<T> for RcStatefulConsumer<T> {
105 fn accept(&mut self, value: &T) {
106 (self.function.borrow_mut())(value)
107 }
108
109 // Use macro to implement conversion methods
110 impl_rc_conversions!(
111 RcStatefulConsumer<T>,
112 BoxStatefulConsumer,
113 BoxConsumerOnce,
114 FnMut(t: &T)
115 );
116}
117
118// Use macro to generate Clone implementation
119impl_consumer_clone!(RcStatefulConsumer<T>);
120
121// Use macro to generate Debug and Display implementations
122impl_consumer_debug_display!(RcStatefulConsumer<T>);