qubit_function/functions/function/rc_function.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026.
4 * Haixing Hu, Qubit Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! Defines the `RcFunction` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// RcFunction - Rc<dyn Fn(&T) -> R>
17// ============================================================================
18
19/// RcFunction - single-threaded function wrapper
20///
21/// A single-threaded, clonable function wrapper optimized for scenarios
22/// that require sharing without thread-safety overhead.
23///
24/// # Features
25///
26/// - **Based on**: `Rc<dyn Fn(&T) -> R>`
27/// - **Ownership**: Shared ownership via reference counting (non-atomic)
28/// - **Reusability**: Can be called multiple times (each call consumes its
29/// input)
30/// - **Thread Safety**: Not thread-safe (no `Send + Sync`)
31/// - **Clonable**: Cheap cloning via `Rc::clone`
32///
33/// # Author
34///
35/// Haixing Hu
36pub struct RcFunction<T, R> {
37 pub(super) function: Rc<dyn Fn(&T) -> R>,
38 pub(super) name: Option<String>,
39}
40
41impl<T, R> RcFunction<T, R> {
42 // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
43 impl_function_common_methods!(
44 RcFunction<T, R>,
45 (Fn(&T) -> R + 'static),
46 |f| Rc::new(f)
47 );
48
49 // Generates: when(), and_then(), compose()
50 impl_shared_function_methods!(
51 RcFunction<T, R>,
52 RcConditionalFunction,
53 into_rc,
54 Function,
55 'static
56 );
57}
58
59// Generates: constant() method for RcFunction<T, R>
60impl_function_constant_method!(RcFunction<T, R>, 'static);
61
62// Generates: identity() method for RcFunction<T, T>
63impl_function_identity_method!(RcFunction<T, T>);
64
65// Generates: Clone implementation for RcFunction<T, R>
66impl_function_clone!(RcFunction<T, R>);
67
68// Generates: Debug and Display implementations for RcFunction<T, R>
69impl_function_debug_display!(RcFunction<T, R>);
70
71// Implement Function trait for RcFunction<T, R>
72impl<T, R> Function<T, R> for RcFunction<T, R> {
73 fn apply(&self, t: &T) -> R {
74 (self.function)(t)
75 }
76
77 // Use macro to implement conversion methods
78 impl_rc_conversions!(
79 RcFunction<T, R>,
80 BoxFunction,
81 BoxFunctionOnce,
82 Fn(t: &T) -> R
83 );
84}