qubit_function/functions/stateful_function/rc_stateful_function.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 `RcStatefulFunction` public type.
12
13#![allow(unused_imports)]
14
15use super::*;
16
17// ============================================================================
18// RcStatefulFunction - Rc<RefCell<dyn FnMut(&T) -> R>>
19// ============================================================================
20
21/// RcStatefulFunction - single-threaded function wrapper
22///
23/// A single-threaded, clonable function wrapper optimized for scenarios
24/// that require sharing without thread-safety overhead.
25///
26/// # Features
27///
28/// - **Based on**: `Rc<RefCell<dyn FnMut(&T) -> R>>`
29/// - **Ownership**: Shared ownership via reference counting (non-atomic)
30/// - **Reusability**: Can be called multiple times (each call consumes
31/// its input)
32/// - **Thread Safety**: Not thread-safe (no `Send + Sync`)
33/// - **Clonable**: Cheap cloning via `Rc::clone`
34/// - **Statefulness**: Can modify internal state between calls
35///
36pub struct RcStatefulFunction<T, R> {
37 pub(super) function: RcStatefulFn<T, R>,
38 pub(super) name: Option<String>,
39}
40
41type RcStatefulFn<T, R> = Rc<RefCell<dyn FnMut(&T) -> R>>;
42
43impl<T, R> RcStatefulFunction<T, R> {
44 // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
45 impl_function_common_methods!(
46 RcStatefulFunction<T, R>,
47 (FnMut(&T) -> R + 'static),
48 |f| Rc::new(RefCell::new(f))
49 );
50
51 // Generates: when(), and_then(), compose()
52 impl_shared_function_methods!(
53 RcStatefulFunction<T, R>,
54 RcConditionalStatefulFunction,
55 into_rc,
56 StatefulFunction,
57 'static
58 );
59}
60
61// Generates: constant() method for RcStatefulFunction<T, R>
62impl_function_constant_method!(RcStatefulFunction<T, R>, 'static);
63
64// Generates: identity() method for RcStatefulFunction<T, T>
65impl_function_identity_method!(RcStatefulFunction<T, T>);
66
67// Generates: Clone implementation for RcStatefulFunction<T, R>
68impl_function_clone!(RcStatefulFunction<T, R>);
69
70// Generates: Debug and Display implementations for RcStatefulFunction<T, R>
71impl_function_debug_display!(RcStatefulFunction<T, R>);
72
73// Implement StatefulFunction trait for RcStatefulFunction<T, R>
74impl<T, R> StatefulFunction<T, R> for RcStatefulFunction<T, R> {
75 fn apply(&mut self, t: &T) -> R {
76 (self.function.borrow_mut())(t)
77 }
78
79 // Use macro to implement conversion methods
80 impl_rc_conversions!(
81 RcStatefulFunction<T, R>,
82 BoxStatefulFunction,
83 BoxFunctionOnce,
84 FnMut(t: &T) -> R
85 );
86}