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