Skip to main content

qubit_function/consumers/stateful_consumer/
rc_stateful_consumer.rs

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