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