Skip to main content

qubit_function/functions/function/
rc_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 `RcFunction` public type.
12
13#![allow(unused_imports)]
14
15use super::*;
16
17// ============================================================================
18// RcFunction - Rc<dyn Fn(&T) -> R>
19// ============================================================================
20
21/// RcFunction - 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<dyn Fn(&T) -> R>`
29/// - **Ownership**: Shared ownership via reference counting (non-atomic)
30/// - **Reusability**: Can be called multiple times (each call consumes its
31///   input)
32/// - **Thread Safety**: Not thread-safe (no `Send + Sync`)
33/// - **Clonable**: Cheap cloning via `Rc::clone`
34///
35pub struct RcFunction<T, R> {
36    pub(super) function: Rc<dyn Fn(&T) -> R>,
37    pub(super) name: Option<String>,
38}
39
40impl<T, R> RcFunction<T, R> {
41    // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
42    impl_function_common_methods!(
43        RcFunction<T, R>,
44        (Fn(&T) -> R + 'static),
45        |f| Rc::new(f)
46    );
47
48    // Generates: when(), and_then(), compose()
49    impl_shared_function_methods!(
50        RcFunction<T, R>,
51        RcConditionalFunction,
52        into_rc,
53        Function,
54        'static
55    );
56}
57
58// Generates: constant() method for RcFunction<T, R>
59impl_function_constant_method!(RcFunction<T, R>, 'static);
60
61// Generates: identity() method for RcFunction<T, T>
62impl_function_identity_method!(RcFunction<T, T>);
63
64// Generates: Clone implementation for RcFunction<T, R>
65impl_function_clone!(RcFunction<T, R>);
66
67// Generates: Debug and Display implementations for RcFunction<T, R>
68impl_function_debug_display!(RcFunction<T, R>);
69
70// Implement Function trait for RcFunction<T, R>
71impl<T, R> Function<T, R> for RcFunction<T, R> {
72    fn apply(&self, t: &T) -> R {
73        (self.function)(t)
74    }
75
76    // Use macro to implement conversion methods
77    impl_rc_conversions!(
78        RcFunction<T, R>,
79        BoxFunction,
80        BoxFunctionOnce,
81        Fn(t: &T) -> R
82    );
83}