Skip to main content

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