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